- 如果是list中存储的是string,int等基本数据类型,直接使用Distinct方法
List<string> lst = new List<string>() {"A","B","C","A" }; var result = lst.Distinct().ToList();
2.如果存储的是类,你需要设定两个类之间重复的标准。
- 实现 IEquatable<T> 接口。
class Program { static void Main(string[] args) { List<Student> stuLst = new List<Student>() { new Student(){ Id =1,Name = "A",Age = 10}, new Student(){ Id =2,Name = "B",Age = 12}, new Student(){ Id =3,Name = "C",Age = 13}, new Student(){ Id =1,Name = "A",Age = 11} }; var results = stuLst.Distinct().ToList(); foreach (var result in results) Console.WriteLine(result.Id + " " + result.Name + " " + result.Age); Console.ReadLine(); } } class Student : IEquatable<Student> { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } /// <summary> /// Standard: If one class‘s Id and Name is the same as antoher class, then they are duplicate. /// </summary> public bool Equals(Student other) { if (Object.ReferenceEquals(other, null)) return false; if (Object.ReferenceEquals(this, other)) return true; return Id.Equals(other.Id) && Name.Equals(other.Name); } // If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects. public override int GetHashCode() { return Id.GetHashCode() ^ Name.GetHashCode(); } }
- 实现 IEqualityComparer<T> 接口
class Program { static void Main(string[] args) { List<Student> stuLst = new List<Student>() { new Student(){ Id =1,Name = "A",Age = 10}, new Student(){ Id =2,Name = "B",Age = 12}, new Student(){ Id =3,Name = "C",Age = 13}, new Student(){ Id =1,Name = "A",Age = 11} }; var results = stuLst.Distinct(new StudentComparer()).ToList(); foreach (var result in results) Console.WriteLine(result.Id + " " + result.Name + " " + result.Age); Console.ReadLine(); } } class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } class StudentComparer : IEqualityComparer<Student> { /// <summary> /// Standard: If one class‘s Id and Name is the same as antoher class, then they are duplicate. /// </summary> public bool Equals(Student x, Student y) { if (Object.ReferenceEquals(x, y)) return true; if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; return x.Id == y.Id && x.Name == y.Name; } public int GetHashCode(Student student) { if (Object.ReferenceEquals(student, null)) return 0; return student.Id.GetHashCode() ^ student.Name.GetHashCode(); } }