问题
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