Created
July 22, 2012 06:49
-
-
Save timvw/3158727 to your computer and use it in GitHub Desktop.
ValueComparer
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 ValueComparer<T> : IEqualityComparer<T> | |
{ | |
private readonly Func<T, object>[] _valueSelectors; | |
private readonly Func<T, int> _hashCodeFunction; | |
public ValueComparer(params Func<T, object>[] valueSelectors) | |
: this(t => t.GetHashCode(), valueSelectors) | |
{ | |
_valueSelectors = valueSelectors; | |
} | |
public ValueComparer(Func<T, int> hashCodeFunction, params Func<T, object>[] valueSelectors) | |
{ | |
_hashCodeFunction = hashCodeFunction; | |
_valueSelectors = valueSelectors; | |
} | |
public bool Equals(T x, T y) | |
{ | |
return _valueSelectors.All(valueSelector => valueSelector(x) == valueSelector(y)); | |
} | |
public int GetHashCode(T obj) | |
{ | |
return _hashCodeFunction(obj); | |
} | |
} |
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
IEnumerable<Contact> contacts = new List<Contact> { | |
new Contact("Tim", "Van Wassenhove"), | |
new Contact("Evy", "Penninckx"), | |
new Contact("Tiebe", "Van Wassenhove"), | |
}; | |
var distinctLastNames = contacts | |
.Distinct(new ValueComparer<Contact>(contact => contact.LastName)) | |
.Select(contact => contact.LastName); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment