两个列表之间的区别 [英] Difference between two lists

查看:73
本文介绍了两个列表之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个泛型列表充满CustomsObjects。

I Have two generic list filled with CustomsObjects.

我要找回这两个列表之间(的项目谁是第一个在没有第二个项目)的第三个区别。

I need to retrieve the difference between those two lists(Items who are in the first without the items in the second one) in a third one.

我想使用。除()是个好主意,但我没有看到如何使用这个..
救命啊!

I was thinking using .Except() was a good idea but I don't see how to use this.. Help!

推荐答案

使用除了是究竟走正道。如果你的类型将覆盖等于 GetHash code ,或者你只在引用类型相等兴趣(即两个引用只有平等的,如果他们指的是完全相同的对象),你可以使用:

Using Except is exactly the right way do go. If your type overrides Equals and GetHashCode, or you're only interested in reference type equality (i.e. two references are only "equal" if they refer to the exact same object), you can just use:

var list3 = list1.Except(list2).ToList();

如果你需要前preSS平等的定制理念,例如通过ID,你需要实施的IEqualityComparer< T> 。例如:

If you need to express a custom idea of equality, e.g. by ID, you'll need to implement IEqualityComparer<T>. For example:

public class IdComparer : IEqualityComparer<CustomObject>
{
    public int GetHashCode(CustomObject co)
    {
        if (co == null)
        {
            return 0;
        }
        return co.Id.GetHashCode();
    }

    public bool Equals(CustomObject x1, CustomObject x2)
    {
        if (object.ReferenceEquals(x1, x2))
        {
            return true;
        }
        if (object.ReferenceEquals(x1, null) ||
            object.ReferenceEquals(x2, null))
        {
            return false;
        }
        return x1.Id == x2.Id;
    }
}

然后使用:

var list3 = list1.Except(list2, new IdComparer()).ToList();

编辑:正如在评论中指出,这将消除任何重复元素;如果你需要重复是preserved,让我们知道...它很可能是最简单的创建从列表2 A组,并使用类似:

var list3 = list1.Where(x => !set2.Contains(x)).ToList();

这篇关于两个列表之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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