使用Linq不等于

Jim*_*mmy 6 c# linq

我在C#app.A和B中有2个列表集合.

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

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

我该怎么做呢?

Ant*_*ram 18

有多种方法可以采取.最简洁的方法是使用Except扩展方法,如果你有覆盖EqualsGetHashCode.如果还没有,还有其他选择.

// 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));
Run Code Online (Sandbox Code Playgroud)

...

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Lar*_*nal 5

如果您为客户对象重写等于,则只需使用

A.Except(B);
Run Code Online (Sandbox Code Playgroud)