Created
April 10, 2013 21:00
-
-
Save caseywatson/5358397 to your computer and use it in GitHub Desktop.
LINQ operators that require an IEqualityComparer<T> suck. Do this instead.
This file contains hidden or 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
| using System; | |
| using System.Collections.Generic; | |
| namespace SpaceX.CDL.Core | |
| { | |
| public class FunctionalEqualityComparer<T> : IEqualityComparer<T> | |
| { | |
| private readonly Func<T, T, bool> comparisonFunction; | |
| public FunctionalEqualityComparer(Func<T, T, bool> comparisonFunction) | |
| { | |
| if (comparisonFunction == null) | |
| throw new ArgumentNullException("comparisonFunction"); | |
| this.comparisonFunction = comparisonFunction; | |
| } | |
| public bool Equals(T x, T y) | |
| { | |
| return comparisonFunction(x, y); | |
| } | |
| public int GetHashCode(T obj) | |
| { | |
| return obj.GetHashCode(); | |
| } | |
| } | |
| } | |
| public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source, Func<T, T, bool> comparisonFunction) | |
| { | |
| if (source == null) | |
| throw new ArgumentNullException("source"); | |
| if (comparisonFunction == null) | |
| throw new ArgumentNullException( "comparisonFunction" ); | |
| return source.Distinct( new FunctionalEqualityComparer<T>( comparisonFunction ) ); | |
| } | |
| public static IEnumerable<T> Distinct<T, U>(this IEnumerable<T> source, Func<T, U> selectorFunction) | |
| { | |
| if (source == null) | |
| throw new ArgumentNullException("source"); | |
| if (selectorFunction == null) | |
| throw new ArgumentNullException("selectorFunction"); | |
| return | |
| source.Distinct( | |
| new FunctionalEqualityComparer<T>( | |
| (x, y) => EqualityComparer<U>.Default.Equals(selectorFunction(x), selectorFunction(y)))); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment