繁体   English   中英

使用Linq不等于

[英]Using Linq not equals

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

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

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

我该怎么做呢?

有多种方法可以采取。 如果你有覆盖EqualsGetHashCode ,最干净的方法是使用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();
    }
}

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

A.Except(B);

扩展为Except,提供您自己的平等,因此您无需更改Equals行为。 我从这里得到了这个:

http://www.codeproject.com/KB/dotnet/LINQ.aspx#distinct

List<Customer> customersA = new List<Customer> { new Customer { Id = 1, Name = "A" }, new Customer { Id = 2, Name = "B" } };
List<Customer> customersB = new List<Customer> { new Customer { Id = 1, Name = "A" }, new Customer { Id = 3, Name = "C" } };

var c = (from custA in customersA
        select custA.Id).Distinct()
             .Except((from custB in customersB
            select custB.Id).Distinct());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM