2013-05-29 30 views
10

List1包含項目{A,B},List2包含項目{A,B,C}。使用Linq除非沒有按照我的想法工作

當我使用除Linq擴展名外,我需要返回{C}。相反,我返回{A,B},如果我在表達式中翻轉列表,結果是{A,B,C}。

我誤解了Except的觀點嗎?有沒有另一個擴展我沒有看到使用?

我已經瀏覽過,並嘗試了一些關於此事的不同的帖子,迄今爲止沒有成功。

var except = List1.Except(List2); //This is the line I have thus far

編輯:是的,我是比較簡單的對象。我從來沒有使用IEqualityComparer,瞭解它很有趣。

謝謝大家的幫助。問題是沒有實現比較器。鏈接的博客文章和下面的示例在哪裏有幫助。

+1

這些清單究竟是什麼? –

+0

什麼是您的項目的數據類型。這是一堂課嗎?這個鏈接可能會幫助你http://stackoverflow.com/questions/1645891/why-isnt-except-linq-comparing-things-properly-using-iequatable – arunlalam

+0

他們是簡單的對象,有一些屬性的時刻。我會查看你的鏈接。 – Schanckopotamus

回答

10

如果要在列表中存儲引用類型,則必須確保有一種方法可以比較對象是否相等。否則,他們將通過比較是否涉及相同的地址進行檢查。

您可以執行IEqualityComparer<T>並將其作爲參數發送到Except()函數。這裏有一個blog post,你可能會發現有幫助。

+0

要清楚這是解決方案,很久以前解決了我的問題,並且是一個可行的選項,具體取決於您的情況。 – Schanckopotamus

6

你只是混淆了參數的順序。我能看到這種混亂出現,因爲official documentation並不太實用,因爲它可以:

通過使用默認的相等比較值進行比較生成兩個序列的差集。

除非你是在集理論精通,它可能不是很清楚什麼set difference實際上是—它不是簡單的什麼是集之間不同。實際上,Except返回第一組中不在第二組中的元素列表。

試試這個:

var except = List2.Except(List1); // { C } 
+0

如果更改列表順序,我會得到{A,B,C} – Schanckopotamus

4
所以只是爲了完整性

...

// Except gives you the items in the first set but not the second 
    var InList1ButNotList2 = List1.Except(List2); 
    var InList2ButNotList1 = List2.Except(List1); 
// Intersect gives you the items that are common to both lists  
    var InBothLists = List1.Intersect(List2); 

編輯:既然你的列表中包含的對象,你需要在的IEqualityComparer通過你的類...在這裏是什麼你除了將看起來像樣本IEqualityComparer基於組成對象... :)

// Except gives you the items in the first set but not the second 
     var equalityComparer = new MyClassEqualityComparer(); 
     var InList1ButNotList2 = List1.Except(List2, equalityComparer); 
     var InList2ButNotList1 = List2.Except(List1, equalityComparer); 
// Intersect gives you the items that are common to both lists  
     var InBothLists = List1.Intersect(List2); 

public class MyClass 
{ 
    public int i; 
    public int j; 
} 

class MyClassEqualityComparer : IEqualityComparer<MyClass> 
{ 
    public bool Equals(MyClass x, MyClass y) 
    { 
     return x.i == y.i && 
       x.j == y.j; 
    } 

    public int GetHashCode(MyClass obj) 
    { 
     unchecked 
     { 
      if (obj == null) 
       return 0; 
      int hashCode = obj.i.GetHashCode(); 
      hashCode = (hashCode * 397)^obj.i.GetHashCode(); 
      return hashCode; 
     } 
    } 
} 
+0

InList1ButNotList2給出{C,B,A},這就是發生了什麼。 – Schanckopotamus

+0

@Schanckopotomus啊......你的列表是對象,它們的屬性是相等的,但是對象沒有引用平等嗎? – Kevin

相關問題