LINQ's Distinct() on a particular property

后端 未结 20 2017
一向
一向 2020-11-21 05:05

I am playing with LINQ to learn about it, but I can\'t figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy

20条回答
  •  走了就别回头了
    2020-11-21 05:54

    Override Equals(object obj) and GetHashCode() methods:

    class Person
    {
        public int Id { get; set; }
        public int Name { get; set; }
    
        public override bool Equals(object obj)
        {
            return ((Person)obj).Id == Id;
            // or: 
            // var o = (Person)obj;
            // return o.Id == Id && o.Name == Name;
        }
        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
    }
    

    and then just call:

    List distinctList = new[] { person1, person2, person3 }.Distinct().ToList();
    

提交回复
热议问题