Skip to content

Instantly share code, notes, and snippets.

@collinsauve
Created December 29, 2015 17:52
Show Gist options
  • Save collinsauve/b7b5cd0d9a03c7a72546 to your computer and use it in GitHub Desktop.
Save collinsauve/b7b5cd0d9a03c7a72546 to your computer and use it in GitHub Desktop.
public static class LambdaComparer
{
/// <summary>
/// Creates an <see cref="IEqualityComparer&lt;T&gt;"/> using the given <paramref name="equalsFunc"/> and a constant <see cref="IEqualityComparer&lt;T&gt;.GetHashCode(T)"/> function.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="equalsFunc">A function to use for <see cref="IEqualityComparer&lt;T&gt;.Equals(T, T)"/></param>
/// <returns>An <see cref="IEqualityComparer&lt;T&gt;"/></returns>
/// <remarks>Since <see cref="IEqualityComparer&lt;T&gt;.GetHashCode(T)"/> will be constant, this comparer will not perform well on large sets. For performance
/// critical code, use <see cref="Create&lt;T&gt;(Func&lt;T, T, bool&gt;, Func&lt;T, int&gt;)"/></remarks>
public static IEqualityComparer<T> Create<T>(Func<T, T, bool> equalsFunc)
{
return Create(equalsFunc, o => 0);
}
/// <summary>
/// Creates an <see cref="IEqualityComparer&lt;T&gt;"/> using the given <paramref name="equalsFunc"/> and <paramref name="hashCodeFunc"/>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="equalsFunc">A function to use for <see cref="IEqualityComparer&lt;T&gt;.Equals(T, T)"/></param>
/// <param name="hashCodeFunc">A function to use for <see cref="IEqualityComparer&lt;T&gt;.GetHashCode(T)"/></param>
/// <returns>An <see cref="IEqualityComparer&lt;T&gt;"/></returns>
public static IEqualityComparer<T> Create<T>(Func<T, T, bool> equalsFunc, Func<T, int> hashCodeFunc)
{
return new LambdaComparer<T>(equalsFunc, hashCodeFunc);
}
}
public class LambdaComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _equalsFunc;
private readonly Func<T, int> _hashCodeFunc;
public LambdaComparer(Func<T, T, bool> equalsFunc, Func<T, int> hashCodeFunc)
{
_equalsFunc = equalsFunc;
_hashCodeFunc = hashCodeFunc;
}
public bool Equals(T x, T y)
{
return _equalsFunc(x, y);
}
public int GetHashCode(T obj)
{
return _hashCodeFunc(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment