Friday, January 7, 2011

Compare IEnumerable collection of custom objects in Linq

To use Linq : Except, Intersect, etc. on custom Class object collection, you need to provide IEqualityComparer, but is so frustrating, to write a class for each of your objects.

I have found that easiest way to avoid writing custom classes is to write one generic class:

public class Comparer<T> : IEqualityComparer<T>
{
    private readonly Func<T, T, bool> _comparer;
    public Comparer(Func<T, T, bool> comparer)
    {
        if (comparer == null) throw new ArgumentNullException("comparer");
        _comparer = comparer;
    }
 
    public bool Equals(T x, T y)
    {
        return _comparer(x, y);
    }
 
    public int GetHashCode(T obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}
 

and then You can write like this

IEnumerable<SPRoleAssignment> roles = fromRoles.Except(toRoles, new Comparer<SPRoleAssignment>((a, b) => a.Member.ID == b.Member.ID));

1 comment: