1. 程式人生 > >List<object>進行Distinct()去重

List<object>進行Distinct()去重

namespace strong equals ole 重寫 自定義對象 pan 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 }

List<object>進行Distinct()去重