IEqualityComparer<TSource> 比较规则

    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 比较规则:

  1. 如果 HashCode 不同,则不运行 Equals , 直接判定为不同
  2. 如果 HashCode 相同,则运行 Equals , 根据 Equals 判定相不相不同
posted @ 2020-11-14 10:15  ChasingDreams  阅读(146)  评论(0编辑  收藏  举报