2010-09-08 32 views
6

Ben ettik 2 liste benim C# app..A koleksiyonları ve Bkullanma Linq değil eşittir

Her iki koleksiyon Kimliği ve Adı attributes.Typically sahip müşteri nesne, A'dan B'ye

daha fazla öğe vardır var

Linq kullanarak, yalnızca kimliği A olan ancak B'de olmayan müşterilere dönmek istiyorum.

Bunu nasıl yaparım?

+0

Ne "a değil koşulunu eşittir üzerinden birleştirmek", demek? –

+0

Sorunuzu biraz daha spesifik hale getirebilirsiniz? – FosterZ

cevap

18

Almak için çeşitli yaklaşımlar vardır. En temiz yaklaşım, Equals ve GetHashCode geçersiz kılmanız durumunda Except uzantı yöntemini kullanmaktır. Eğer sahip değilseniz başka seçenekler de var.

// 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(); 
    } 
} 
+0

Ur yorumları için teşekkürler ... Bu satırdan: listA.Where (a =>! ListB.Any (b => b.Id == a.Id)); nasıl üçüncü bir liste "C" alacağım Bu A dan gelen müşteri nesneleri B'de mevcut değil mi? – Jimmy

+0

@Jimmy, 'Liste listC = listA.Where (a => listB.Any (b => b.Id == a.Id)!) ToList();.!' –

+0

Teşekkür Anthony Pegram Bu benim için harika çalışıyor Ben kullandım: listA.Where (a =>! ListB.Any (b => b.Id == a.Id)); yaklaşım. – Jimmy

5

geçersiz kılma müşteri nesnesi için Eşittir sen, o zaman sadece

A.Except(B); 
4

ihtiyacınız kalmaz Kendi eşitliği sağlayan hariç ayrıntılı şekilde kullanırsanız Eşit davranışını değiştirmek için. Bu buradan aldı:

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()); 
+0

Bu durumda, 'var c',' customersA''dan benzersiz, benzersiz eşlemlerin bir dizisini temsil eden IEnumerable 'olacaktır. "Müşteri" nesnelerini elde etmek için, bu sonucun "customersA" dan nesnelere ulaşmak için tekrar kullanılması gerekir. –