LINQ如何去掉重复记录
id n1 n2 n3
1 c1 c2 c3
2 c2 c3 c1
3 c3 c1 c2
4 c4 c1 c5
1,2,3行都只有c1,c2,c3虽然位置不一下,但咱们都把它当成重复的.要怎么能把它删除掉?
[解决办法]
- C# code
using System;using System.Collections.Generic;using System.Linq;class Line{ public int id { get; set; } public string n1 { get; set; } public string n2 { get; set; } public string n3 { get; set; }}class Tools:IEqualityComparer<Line>{ private string MakeSort(ref Line x) { string tmp; if(x.n1.CompareTo(x.n2)<0) { tmp = x.n1; x.n1 = x.n2; x.n2 = tmp; } if (x.n2.CompareTo(x.n3) < 0) { tmp = x.n2; x.n2 = x.n3; x.n3 = tmp; } if (x.n1.CompareTo(x.n2) < 0) { tmp = x.n1; x.n1 = x.n2; x.n2 = tmp; } return x.n1 + x.n2 + x.n3; } #region IEqualityComparer<Line> 成员 public bool Equals(Line x, Line y) { return MakeSort(ref x) == MakeSort(ref y); } public int GetHashCode(Line obj) { return MakeSort(ref obj).GetHashCode(); } #endregion}class MyClass{ static void Main(string[] args) { //准备 Line[] list = { new Line{ id = 1, n1 = "c1", n2 = "c2", n3 = "c3" }, new Line{ id = 2, n1 = "c2", n2 = "c3", n3 = "c1" }, new Line{ id = 3, n1 = "c3", n2 = "c1", n3 = "c2" }, new Line{ id = 4, n1 = "c4", n2 = "c1", n3 = "c5" }, }; //执行 Line[] listOk = list.Distinct(new Tools()).ToArray(); //验证 foreach (var x in listOk) { Console.WriteLine(x.id + " " + x.n1 + " " + x.n2 + " " + x.n3); } //1 c3 c2 c1 //4 c5 c4 c1 Console.ReadKey(); }}