2011-11-29 54 views
10

我有兩個名單見下文.....結果是回來爲空相交兩者之間不工作

List<Pay>olist = new List<Pay>(); 
List<Pay> nlist = new List<Pay>(); 
Pay oldpay = new Pay() 
{ 
    EventId = 1, 
    Number = 123,       
    Amount = 1 
}; 

olist.Add(oldpay); 
Pay newpay = new Pay() 
{ 
    EventId = 1, 
    Number = 123,       
    Amount = 100 
}; 
nlist.Add(newpay); 
var Result = nlist.Intersect(olist); 

任何線索,爲什麼?

+0

假設工資平等是事件ID,數量和金額,沒有什麼共同在這兩個名單,因此沒有相交。換句話說,你在這裏沒有定義平等。 –

+0

你是什麼意思在這裏沒有定義平等?唯一不同的元素是金額= 100 – user570715

+0

沒有什麼在_why_指出的問題'oldpay'應該等於'newpay'。 –

回答

21

你需要重寫你的PayEqualsGetHashCode方法,否則當兩個實例被認爲是相等Intersect不知道。它怎麼能猜出確定平等的是EventIdoldPaynewPay是不同的實例,所以默認情況下它們並不相同。

您可以覆蓋方法Pay這樣的:

public override int GetHashCode() 
{ 
    return this.EventId; 
} 

public override bool Equals(object other) 
{ 
    if (other is Pay) 
     return ((Pay)other).EventId == this.EventId; 
    return false; 
} 

另一種選擇是實施IEqualityComparer<Pay>,它作爲參數傳遞給Intersect

public class PayComparer : IEqualityComparer<Pay> 
{ 
    public bool Equals(Pay x, Pay y) 
    { 
     if (x == y) // same instance or both null 
      return true; 
     if (x == null || y == null) // either one is null but not both 
      return false; 

     return x.EventId == y.EventId; 
    } 


    public int GetHashCode(Pay pay) 
    { 
     return pay != null ? pay.EventId : 0; 
    } 
} 

... 

var Result = nlist.Intersect(olist, new PayComparer()); 
+2

或者你可以寫你自己的比較器:http://msdn.microsoft.com/en-us/library/234b841s.aspx – mydogisbox

+0

@mydogisbox,是的,我其實編輯我的回答提到這一點,當你評論;) –

+0

或者你可以使'Pay'類型爲一個'struct'來爲你完成它,儘管默認實現是慢的,因爲它使用了反射。 – Gebb

0

Intersect大概只能添加對象當Pay的同一個實例在List中時。由於oldPaynewPay被實例化,他們被認爲是不相等的。

Intersect使用Equals方法來比較的對象。如果不重寫它保持Object類的行爲相同:返回true只有兩個是對象相同的實例。

你應該Pay覆蓋Equals方法。

//in the Pay class 
    public override bool Equals(Object o) { 
     Pay pay = o as Pay; 
     if (pay == null) return false; 
     // you haven't said if Number should be included in the comparation 
     return EventId == pay.EventId; // && Number == pay.Number; (if applies) 
    } 
0

對象是引用類型。當你創建兩個對象時,你有兩個唯一的引用。他們會比較平等的唯一方法是:

object a = new object(); 
object b = a; 

在這種情況下,(a == b)爲真。閱讀上reference VS value類型和objects

並修復您的問題,重寫equals和GetHashCode,托馬斯Levesque的指出。