原文:List<object>进行Distinct()去重
有时我们会对一个list<T>集合里的数据进行去重,C#提供了一个Distinct()方法直接可以点得出来。如果list<T>中的T是个自定义对象时直接对集合Distinct是达不到去重的效果。我们需要新定义一个去重的类并继承IEqualityComparer接口重写Equals和GetHashCode方法,如下Demo
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 5 namespace MyTestCode 6 { 7 /// <summary> 8 /// Description of DistinctDemo. 9 /// </summary> 10 public class DistinctDemo 11 { 12 private static List<Student> list; 13 public DistinctDemo() 14 { 15 } 16 17 public static void init() 18 { 19 list = new List<Student>{ 20 new Student{ 21 Id=1, 22 Name="xiaoming", 23 Age=22 24 }, 25 new Student{ 26 Id=2, 27 Name="xiaohong", 28 Age=23 29 }, 30 new Student{ 31 Id=2, 32 Name="xiaohong", 33 Age=23 34 }, 35 }; 36 } 37 38 public void Display() 39 { 40 list = list.Distinct(new ListDistinct()).ToList(); 41 foreach (var element in list) { 42 Console.WriteLine(element.Id +"/"+element.Name+"/"+element.Age); 43 } 44 } 45 46 } 47 48 public class Student 49 { 50 public int Id{get;set;} 51 public string Name{get;set;} 52 public int Age{get;set;} 53 } 54 55 public class ListDistinct : IEqualityComparer<Student> 56 { 57 public bool Equals(Student s1,Student s2) 58 { 59 return (s1.Name == s2.Name); 60 } 61 62 public int GetHashCode(Student s) 63 { 64 return s==null?0:s.ToString().GetHashCode(); 65 } 66 } 67 }
时间: 2024-10-07 22:41:23