Created
October 1, 2012 09:09
-
-
Save toburger/3810474 to your computer and use it in GitHub Desktop.
Enumerable Extension Method to Distinct or Union IEnumerable(s) by a property without the need to create an IEqualityComparer<T> implementation.
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
static class EnumerableExtensions | |
{ | |
public static IEnumerable<T> Distinct<T, TProperty>( | |
this IEnumerable<T> source, | |
Expression<Func<T, TProperty>> propertyExpression) | |
{ | |
return source.Distinct( | |
new PropertyExpressionComparer<T, TProperty>(propertyExpression)); | |
} | |
public static IEnumerable<T> Union<T, TProperty>( | |
this IEnumerable<T> first, | |
IEnumerable<T> second, | |
Expression<Func<T, TProperty>> propertyExpression) | |
{ | |
return first.Union( | |
second, | |
new PropertyExpressionComparer<T, TProperty>(propertyExpression)); | |
} | |
private class PropertyExpressionComparer<T, TProperty> : IEqualityComparer<T> | |
{ | |
private readonly PropertyInfo _propertyInfo; | |
public PropertyExpressionComparer(Expression<Func<T, TProperty>> propertyExpression) | |
{ | |
string propertyName = ((MemberExpression)propertyExpression.Body).Member.Name; | |
_propertyInfo = typeof(T).GetProperty(propertyName); | |
} | |
public bool Equals(T x, T y) | |
{ | |
return _propertyInfo.GetValue(x).Equals(_propertyInfo.GetValue(y)); | |
} | |
public int GetHashCode(T obj) | |
{ | |
return _propertyInfo.GetValue(obj).GetHashCode(); | |
} | |
} | |
} |
Author
toburger
commented
Oct 1, 2012
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment