Skip to content

Instantly share code, notes, and snippets.

@HaanstootZA
Created January 20, 2023 11:29
Show Gist options
  • Select an option

  • Save HaanstootZA/2bd4c2ad65df70e52e7b59d6a6e26a1c to your computer and use it in GitHub Desktop.

Select an option

Save HaanstootZA/2bd4c2ad65df70e52e7b59d6a6e26a1c to your computer and use it in GitHub Desktop.
public class DelegateEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> equalityPredicate;
private readonly Func<T, int> hashCodePredicate;
public DelegateEqualityComparer(Func<T, T, bool> equalityPredicate)
: this (equalityPredicate, null)
{
}
public DelegateEqualityComparer(Func<T, T, bool> equalityPredicate, Func<T, int> hashCodePredicate)
{
this.equalityPredicate = equalityPredicate;
this.hashCodePredicate = hashCodePredicate;
}
public bool Equals(T? x, T? y)
{
if (x is null && y is null)
return true;
if (x is null || y is null)
return false;
return equalityPredicate.Invoke(x, y);
}
public int GetHashCode([DisallowNull] T obj)
{
return hashCodePredicate?.Invoke(obj) ?? obj.GetHashCode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment