使用Linq不等于

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

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

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

我该怎么做呢?

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

 // have you overriden Equals/GetHashCode? IEnumerable resultsA = listA.Except(listB); // no override of Equals/GetHashCode? Can you provide an IEqualityComparer? IEnumerable resultsB = listA.Except(listB, new CustomerComparer()); // Comparer shown below // no override of Equals/GetHashCode + no IEqualityComparer implementation? IEnumerable resultsC = listA.Where(a => !listB.Any(b => b.Id == a.Id)); // are the lists particularly large? perhaps try a hashset approach HashSet customerIds = new HashSet(listB.Select(b => b.Id).Distinct()); IEnumerable resultsD = listA.Where(a => !customerIds.Contains(a.Id)); 

 class CustomerComparer : IEqualityComparer { 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 customersA = new List { new Customer { Id = 1, Name = "A" }, new Customer { Id = 2, Name = "B" } }; List customersB = new List { 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());