[英]Using Linq not equals
我在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();
}
}
如果您為客戶對象重寫等於,則只需使用
A.Except(B);
擴展為Except,提供您自己的平等,因此您無需更改Equals行為。 我從這里得到了這個:
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.