Skip to content

Instantly share code, notes, and snippets.

@beufordy3k
Created January 22, 2016 19:30
Show Gist options
  • Save beufordy3k/e49b2a4bfde96c45e1f0 to your computer and use it in GitHub Desktop.
Save beufordy3k/e49b2a4bfde96c45e1f0 to your computer and use it in GitHub Desktop.
Use a lambda for comparison as an IEqualityComparer<T>
public class LambdaComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _lambdaComparer;
private readonly Func<T, int> _lambdaHash;
public LambdaComparer(Func<T, T, bool> lambdaComparer) :
this(lambdaComparer, o => 0)
{
}
public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash)
{
if (lambdaComparer == null)
throw new ArgumentNullException(nameof(lambdaComparer));
if (lambdaHash == null)
throw new ArgumentNullException(nameof(lambdaHash));
_lambdaComparer = lambdaComparer;
_lambdaHash = lambdaHash;
}
public bool Equals(T x, T y)
{
return _lambdaComparer(x, y);
}
public int GetHashCode(T obj)
{
return _lambdaHash(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment