Skip to content

Instantly share code, notes, and snippets.

@zxsanny
Last active July 17, 2020 15:14
Show Gist options
  • Save zxsanny/7451181 to your computer and use it in GitHub Desktop.
Save zxsanny/7451181 to your computer and use it in GitHub Desktop.
Lambda Equality Comparer
public class EqualityComparerFactory
{
private sealed class Impl<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> Eq;
private readonly Func<T, int> HashFunc;
public Impl(Func<T, T, bool> eq, Func<T, int> hashFunc)
{
Eq = eq;
HashFunc = hashFunc;
}
public bool Equals(T left, T right)
{
return Eq(left, right);
}
public int GetHashCode(T obj)
{
return HashFunc(obj);
}
}
public static IEqualityComparer<T> Create<T>(Func<T, T, bool> eq, Func<T, int> hashFunc )
{
return new Impl<T>(eq, hashFunc);
}
}
var comparer = EqualityComparerFactory.Create<TileTagModel>((a,b) => a.Name == b.Name && a.IsDefault == b.IsDefault, model => model.Name.GetHashCode() + model.IsDefault.GetHashCode());
Assert.That(tags, Is.EquivalentTo(expected).Using(comparer));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment