List <object> Distinct () deduplication, objectdistinct
Sometimes we deduplicate the data in a list <T> set. C # provides a Distinct () method that can be clicked directly. If T in list <T> is a custom object, the Distinct effect cannot be achieved for the set Distinct. We need to define a new de-duplicated class and inherit the IEqualityComparer interface to override the Equals and GetHashCode methods. The following 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 DistinctDemo11 {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=2224 },25 new Student{26 Id=2,27 Name="xiaohong",28 Age=2329 },30 new Student{31 Id=2,32 Name="xiaohong",33 Age=2334 },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 Student49 {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 }