Skip to content

Instantly share code, notes, and snippets.

@timvw
Created July 27, 2012 08:05
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 timvw/3186756 to your computer and use it in GitHub Desktop.
Save timvw/3186756 to your computer and use it in GitHub Desktop.
Chained comparisions
public class ChainedComparer<T> : IComparer<T>
{
private readonly Func<T, T, int>[] _compareFunctions;
public ChainedComparer(params Func<T, T, int>[] compareFunctions)
{
_compareFunctions = compareFunctions;
}
public ChainedComparer(params Func<T, IComparable>[] comparableValueSelectors)
{
_compareFunctions = comparableValueSelectors
.Select<Func<T, IComparable>, Func<T, T, int>>(x => (a, b) => x(a).CompareTo(x(b)))
.ToArray();
}
public int Compare(T x, T y)
{
return _compareFunctions.Select(func => func(x, y)).FirstOrDefault(result => result != 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment