Skip to content

Instantly share code, notes, and snippets.

@marcofranssen
Last active October 2, 2015 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcofranssen/2198967 to your computer and use it in GitHub Desktop.
Save marcofranssen/2198967 to your computer and use it in GitHub Desktop.
Gist related to my "Delegate your equality comparisons" blogpost on http://marcofranssen.nl
public static class CompareExtensions
{
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> items, Func<T, T, bool> equals, Func<T, int> hashCode)
{
return items.Distinct(new DelegateEqualityComparer<T>(equals, hashCode));
}
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> items, Func<T, T, bool> equals)
{
return items.Distinct(new DelegateEqualityComparer<T>(equals, null));
}
}
public class DelegateEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _equals;
private readonly Func<T, int> _hashCode;
public DelegateEqualityComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
{
_equals = equals;
_hashCode = hashCode;
}
public bool Equals(T x, T y)
{
return _equals(x, y);
}
public int GetHashCode(T obj)
{
if (_hashCode != null)
return _hashCode(obj);
return obj.GetHashCode();
}
}
public class PersonLastNameEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.LastName == y.LastName;
}
public int GetHashCode(Person obj)
{
return obj.LastName.GetHashCode();
}
}
public class ProductIdEqualityComparer : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{
return x.Id == y.Id;
}
public int GetHashCode(Product obj)
{
return obj.Id.GetHashCode();
}
}
public class ProductPriceEqualityComparer : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{
return x.Price == y.Price;
}
public int GetHashCode(Product obj)
{
return obj.Price.GetHashCode();
}
}
_products.Distinct((x, y) => x.Id == y.Id, x => x.Id.GetHashCode());
_products.Distinct((x, y) => x.Price == y.Price, x => x.Price.GetHashCode());
_persons.Distinct((x, y) => x.LastName == y.LastName, x => x.LastName.GetHashCode());
_persons.Distinct((x, y) => x.FirstName == y.FirstName, x => x.FirstName.GetHashCode());
_persons.Distinct((x, y) => x.Address.City == y.Address.City, x => x.Address.City.GetHashCode());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment