tags:

views:

41

answers:

1

I have two lists:

List<User> collection1 = new List<User>();
List<User> collection2 = new List<User>();

1) I have to get all items common to both of the lists using LINQ. However, the class User has a lot of properties and I just want to compare FirstName and LastName.

2) How can I get the items in collection1 but not in collection2 using the same comparison rule?

+3  A: 

Use Enumerable.Intersect for the first question and Enumerable.Except for the second. To wit:

var common = collection1.Intersect(collection2, new UserEqualityComparer());
var difference = collection1.Except(collection2, new UserEqualityComparer());

Here, of course, I am assuming that UserEqualityComparer implements IEqualityComparer<User> like so:

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();
    }
}
Jason
Do you need to explicitly define the `GetHashCode` method? I've done this before but don't remember needing to do that.
Kirk Broadhurst
@Kirk: You have to provide an implementation of `GetHashCode` to satisfy the `IEqualityComparer<>` interface, and since `Intersect` and `Except` will almost certainly be calling it then you need to make sure that you implement it properly!
LukeH