原文鏈接:https://blog.csdn.net/daigualu/article/details/70800012
.NET中list的擴展方法Distinct可以去掉重復的元素,分別總結默認去重和自定義去重。
class Program { static void Main(string[] args) { //Distinct去重 //默認去重 List<int> list1 = new List<int> {3, 9, 2, 3, 9}; List<int> list2 = list1.Distinct().ToList(); //出去重復元素,列表變為{3,9,2} //自定義去重 List<Test> list3 = new List<Test>(); list3.Add(new Test(){Data=3}); list3.Add(new Test() { Data = 9 }); list3.Add(new Test() { Data = 2 }); list3.Add(new Test() { Data = 3 }); list3.Add(new Test() { Data = 9 }); List<Test> list4 = list3.Distinct(new TestDuplicateDefine()).ToList();//變為3項 } public class Test { public int Data { get; set; } } public class TestDuplicateDefine: IEqualityComparer<Test> { public bool Equals(Test x, Test y) { return x.Data == y.Data; } public int GetHashCode(Test obj) { return obj.ToString().GetHashCode(); } } }