class Program
{
static void Main(string[] args)
{
List<People> peoples = new List<People>
{
new People{ ID=1,Name="xxx" },
//new People{ ID=1,Name="xxx" },
new People{ID=2,Name="yyy" },
};
peoples = peoples.Distinct(new Filter()).ToList();
Console.WriteLine("Hello World!" + peoples.Count);
}
}
public class Filter : IEqualityComparer<People>
{
public bool Equals([AllowNull] People x, [AllowNull] People y)
{
Console.WriteLine($"Equals->{x.ID},{y.ID}");
return x.ID == y.ID;
}
public int GetHashCode([DisallowNull] People obj)
{
Console.WriteLine($"GetHashCode->{obj.ID}");
return obj.ID;
}
}
IEqualityComparer
- 如果 HashCode 不同,则不运行 Equals , 直接判定为不同
- 如果 HashCode 相同,则运行 Equals , 根据 Equals 判定相不相不同