爲第二的第一個問題和Enumerable.Except使用Enumerable.Intersect。即:
var common = collection1.Intersect(collection2, new UserEqualityComparer());
var difference = collection1.Except(collection2, new UserEqualityComparer());
在這裏,當然,我假設UserEqualityComparer
實現IEqualityComparer<User>
像這樣:
class UserEqualityComparer : IEqualityComparer<User> {
public bool Equals(User x, User y) {
if (Object.ReferenceEquals(x, y)) {
return true;
}
if (x == null || y == null) {
return false;
}
return x.FirstName == y.FirstName && x.LastName == y.LastName;
}
public int GetHashCode(User obj) {
if (obj == null) {
return 0;
}
return 23 * obj.FirstName.GetHashCode() + obj.LastName.GetHashCode();
}
}
你需要明確定義'GetHashCode'方法?我之前做過這個,但不記得需要這樣做。 – 2010-10-21 11:25:47
@Kirk:你必須提供GetHashCode'的'的實現,以滿足'的IEqualityComparer <>'接口,並自'Intersect'和'Except'幾乎肯定會然後調用它,你需要確保你實現它正確! – LukeH 2010-10-21 11:41:25