.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();
- }
- }
- }
来源: http://www.bubuko.com/infodetail-3118061.html