Skip to content

Instantly share code, notes, and snippets.

@caseywatson
Created April 10, 2013 21:00
Show Gist options
  • Select an option

  • Save caseywatson/5358397 to your computer and use it in GitHub Desktop.

Select an option

Save caseywatson/5358397 to your computer and use it in GitHub Desktop.
LINQ operators that require an IEqualityComparer<T> suck. Do this instead.
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