c# – Set operations using a specific comparison rule – Education Career Blog

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?

,

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();
    }
}

Leave a Comment