原文链接: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(); } } }