List<object>进行Distinct()去重

2023-05-16,,

有时我们会对一个list<T>集合里的数据进行去重,C#提供了一个Distinct()方法直接可以点得出来。如果list<T>中的T是个自定义对象时直接对集合Distinct是达不到去重的效果。我们需要新定义一个去重的类并继承IEqualityComparer接口重写Equals和GetHashCode方法,如下Demo

 using System;
using System.Collections.Generic;
using System.Linq; namespace MyTestCode
{
/// <summary>
/// Description of DistinctDemo.
/// </summary>
public class DistinctDemo
{
private static List<Student> list;
public DistinctDemo()
{
} public static void init()
{
list = new List<Student>{
new Student{
Id=,
Name="xiaoming",
Age=
},
new Student{
Id=,
Name="xiaohong",
Age=
},
new Student{
Id=,
Name="xiaohong",
Age=
},
};
} public void Display()
{
list = list.Distinct(new ListDistinct()).ToList();
foreach (var element in list) {
Console.WriteLine(element.Id +"/"+element.Name+"/"+element.Age);
}
} } public class Student
{
public int Id{get;set;}
public string Name{get;set;}
public int Age{get;set;}
} public class ListDistinct : IEqualityComparer<Student>
{
public bool Equals(Student s1,Student s2)
{
return (s1.Name == s2.Name);
} public int GetHashCode(Student s)
{
return s==null?:s.ToString().GetHashCode();
}
}
}

List<object>进行Distinct()去重的相关教程结束。

《List<object>进行Distinct()去重.doc》

下载本文的Word格式文档,以方便收藏与打印。