Last active
July 17, 2020 15:14
-
-
Save zxsanny/7451181 to your computer and use it in GitHub Desktop.
Lambda Equality Comparer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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