c# – 使用Linq不等于

前端之家收集整理的这篇文章主要介绍了c# – 使用Linq不等于前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在C#app.A和B中有2个列表集合.

两个集合都有客户对象,具有Id和Name属性.通常,A有比B更多的项目.

使用Linq,我想只返回ID在A但不在B中的客户.

我该怎么做呢?

解决方法

有多种方法可以采取.如果你有覆盖Equals和GetHashCode,最干净的方法是使用Except扩展方法.如果还没有,还有其他选择.
// 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();
    }
}
原文链接:https://www.f2er.com/csharp/98773.html

猜你在找的C#相关文章