找到两个集合在C#中的补最快的方法 [英] Quickest way to find the complement of two collections in C#

查看:162
本文介绍了找到两个集合在C#中的补最快的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种类型的两个集合的的ICollection 的;的 C1 的和的 C2 的。我想找到的一组项目是中的 C2 的不在 C1 的,其中争取平等的启发是的标识的物业。MyType的

I have two collections of type ICollection; c1 and c2. I'd like to find the set of items that are in c2 that are not in c1 where the heuristic for equality is the Id property on MyType.

什么是在C#中执行这一最快捷的方式。

What is the quickest way to perform this in C#.

编辑:C#版本= 3.0

C# version = 3.0

推荐答案

使用的 Enumerable.Except 并专门的overload 接受一个的IEqualityComparer<&MyType的GT;

var complement = c2.Except(c1, new MyTypeEqualityComparer());

请注意,这会产生差集,从而在 C2 只会出现在结果的IEnumerable<&MyType的GT; 一次。在这里,您需要执行的IEqualityComparer< MyType的> ,就像这样

Note that this produces the set difference and thus duplicates in c2 will only appear in the resulting IEnumerable<MyType> once. Here you need to implement IEqualityComparer<MyType> as something like

class MyTypeEqualityComparer : IEqualityComparer<MyType> {
    public bool Equals(MyType x, MyType y) {
        return x.Id.Equals(y.Id);
    }

    public int GetHashCode(MyType obj) {
        return obj.Id.GetHashCode();
    }
}

这篇关于找到两个集合在C#中的补最快的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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