Compare 2 List using Except [duplicate]

纵饮孤独 提交于 2020-06-29 03:39:14

问题


I have 2 List<Animal> which I would like to compare and find the difference between the 2 List<Animal> objects.

Animal object contains the following properties.

Id

Name

Age

List list1 has a count of 10 Animal objects in it, where as list2 has another 10 Animal objects in it. In these 2 Lists there are 2 items (Animal objects that the same)

When I use the Except function, I was hoping that remainingList will contain Only the objects that aren't common between the 2 list. However, remainingList contains a copy of list1 instead.

How can I solve this ?

 List<Animal> remainingList = list1.Except(list2).toListAsync();

回答1:


You need to Override Equal and GetHashCode in your class. Something like this:

public class Animal
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public override bool Equals(object obj)
    {
        if (!(obj is Animal))
            return false;
        var p = (Animal)obj;
        return p.Id == Id && p.Name == Name && p.Age == Age;
    }

    public override int GetHashCode()
    {
        return String.Format("{0}|{1}|{2}", Id, Name, Age).GetHashCode();
    }
}

Or with newer versions of C# you can:

public override int GetHashCode() => $"{Id}|{Name}|{Age}".GetHashCode();


来源:https://stackoverflow.com/questions/52738755/compare-2-list-using-except

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!