使用Except比较2个列表 [英] Compare 2 List using Except
问题描述
我有2个List<Animal>
,我想进行比较并找到2个List<Animal>
对象之间的差异.
I have 2 List<Animal>
which I would like to compare and find the difference between the 2 List<Animal>
objects.
Animal
对象包含以下属性.
Id
名称
年龄
列表list1
中有10个Animal
对象,其中list2
中还有10个Animal
对象.在这2个列表中,有2个项目(Animal
相同的对象)
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)
当我使用Except
函数时,我希望remainingList
仅包含两个列表之间不常见的对象.但是,remainingList
包含list1
的副本.
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.
我该如何解决?
List<Animal> remainingList = list1.Except(list2).toListAsync();
推荐答案
您需要在课程中覆盖Equal
和GetHashCode
.像这样:
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();
}
}
或者使用更新版本的C#,您可以:
Or with newer versions of C# you can:
public override int GetHashCode() => $"{Id}|{Name}|{Age}".GetHashCode();
这篇关于使用Except比较2个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!