2011-01-21 59 views
0

我有一個班級員工的屬性名稱和ID如何比較數組?

我有一個數組Employee [] A另一個數組Employee [] B.如何比較兩個數組並刪除B中不存在的值來自A?

+0

offtop:奇怪標籤 「C#-4.0」。也許「C#4.0」? : - \ – SeeSharp 2011-01-21 05:21:51

+0

@SeeSharp:這是C#4.0的通用標籤。 – jason 2011-01-21 05:22:48

+0

你的意思是屬性而不是屬性? – Simon 2011-01-21 05:26:24

回答

7
var intersection = A.Intersect(B).ToArray(); 

注意,這裏使用了默認IEqualityComparer<Employee>它只是將是一個參考比較,除非你覆蓋EqualsGetHashCode。或者,您可以實施IEqualityComparer<Employee>並使用Intersect的超載,該過載以IEqualityComparer<Employee>爲例。

0

你可以使用System.Collections.Generic?

我會做這樣的事情:

var listA = new List<Employee>(A); 
var listB = new List<Employee>(B); //not sure if arrays implement contains, may not need this line 

A = listA.where(e => listB.Contains(e)).toArray(); 

希望有所幫助。

0

爲了說明傑森的建議(基於ID的比較):

class IDEmployeeComparer : IEqualityComparer<Employee> 
{ 
    public bool Equals(Employee first, Employee second) 
    { 
     return (first.ID == second.ID); 
    } 

    public int GetHashCode(Employee employee) 
    { 
     return employee.ID 
    } 
} 

...

var intersection = A.Intersect(B, new IDEmployeeComparer()).ToArray(); 

Jon Skeet's misc library允許指定所述比較器的內聯,而無需創建一個單獨的類

0
Employee[] c = (from d in a where !b.Contains<Employee>(d) select d).ToArray<Employee>();