C# Distinct去重,重写IEqualityComparer

public class Student
    {
      public int Age { get; set; }
      public string Name { get; set; }
      public string Adress { get; set; }
    }

  

List<Student> list = new List<Student>()
      { 
      new Student(){Age=21,Name="Jack",Adress="Shenzhen"},
      new Student(){Age=21,Name="Jack",Adress="GuangZhou"}
      };
      var distinct = list.Distinct(new StudentComparer());

  

由于Distinct 直接获取对象的HashCode,用HashCode进行比较的速度比 Equals 方法更快,

因此IEqualityComparer内部会在使用 Equals 前先使用 GetHashCode 方法,在两个对象的HashCode都相同时即刻判断对象相等。

而当两个对象HashCode不相同时, Equals 方法就会被调用,对要比较的对象进行判断。

由于在上例中list中的两个引用实际上是两个不同的对象,因此HashCode必定不相同

所以要触发Equlas方法,我们需要改 GetHashCode ,让它返回相同的常量

public class StudentComparer : IEqualityComparer<Student>
    {
      public bool Equals(Man x, Man y)
      {
        return x.Age == y.Age
          && x.Name == y.Name;
      }
 
      public int GetHashCode(Man obj)
      {
        return 1;
      }
    }

  

posted @ 2020-07-13 14:03  一个有梦想的男孩  阅读(376)  评论(1编辑  收藏  举报