2010-09-08 72 views
6

我在我的C#app..A 2個列表收藏和B.使用LINQ不等於

兩個集合有客戶對象,它具有標識和名稱attributes.Typically,A比B.

多個項目

使用Linq,我只想返回Id爲A但不在B中的客戶。

我該如何做?

+0

你是什麼意思, 「加入一個不等於條件」? – 2010-09-08 15:51:12

+0

你可以讓你的問題更具體一點嗎? – FosterZ 2010-09-08 15:51:23

回答

18

有多種方法可以採取。如果您覆蓋了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(); 
    } 
} 
+0

感謝您的評論...從這一行:listA.Where(a =>!listB.Any(b => b.Id == a.Id));如何獲得第三個列表「C」 哪些A中的客戶對象不在B中? – Jimmy 2010-09-08 16:11:50

+0

@Jimmy,'List listC = listA.Where(a =>!listB.Any(b => b.Id == a.Id))。ToList();' – 2010-09-08 16:14:34

+0

Thanks Anthony Pegram!This works great for me !我用:listA.Where(a =>!listB.Any(b => b.Id == a.Id));做法。 – Jimmy 2010-09-08 17:09:01

5

如果你重載equals爲你的客戶對象,那麼就使用

A.Except(B); 
4

擴展上除了提供自己的平等,所以你不需要改變您的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()); 
+0

在這種情況下,'var c'將是'IEnumerable ',表示來自'customersA'的唯一的,不匹配的ID序列。爲了得到'Customer'對象,這個結果需要再次用來從'customersA'中提取對象。 – 2010-09-08 16:24:45