使用LINQ不等于 [英] Using Linq not equals

查看:720
本文介绍了使用LINQ不等于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2列表收藏在我的C#app..A和B

I've 2 list collections in my C# app..A and B.

这两个集合有具有标识和名称attributes.Typically,A有超过B项。客户对象

Both the collections have customer object which has Id and Name attributes.Typically, A has more items than B.

使用LINQ,我想只返回客户的ID是A,但没有B中。

Using Linq,I want to return only those customers whose Id is in A but not in B.

我如何做到这一点?

推荐答案

有采取多种方式。最简洁的方法是使用除了扩展方法,如果你已经重写等于 GetHash $ C $ç。如果你还没有,还有其他的选择。

There are multiple approaches to take. The cleanest approach is to use the Except extension method if you have overriden Equals and GetHashCode. If you have not, there are other options.

// have you overriden Equals/GetHashCode?
IEnumerable<Customer> resultsA = listA.Except(listB);

// no override of Equals/GetHashCode? Can you provide an IEqualityComparer<Customer>?
IEnumerable<Customer> resultsB = listA.Except(listB, new CustomerComparer()); // Comparer shown below

// no override of Equals/GetHashCode + no IEqualityComparer<Customer> implementation?
IEnumerable<Customer> resultsC = listA.Where(a => !listB.Any(b => b.Id == a.Id));

// are the lists particularly large? perhaps try a hashset approach 
HashSet<int> customerIds = new HashSet<int>(listB.Select(b => b.Id).Distinct());
IEnumerable<Customer> resultsD = listA.Where(a => !customerIds.Contains(a.Id));

...

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

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

这篇关于使用LINQ不等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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