使用Except比较2个列表 [英] Compare 2 List using Except

查看:109
本文介绍了使用Except比较2个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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();

推荐答案

您需要在课程中覆盖EqualGetHashCode.像这样:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆