Another missing method for IEnumerable<T>
Currently there are two overloads for OrderBy on Enumerable:
- OrderBy(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
- OrderBy(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
Because i don’t want to implement an IComparer<TKey> each time i have implemented the following class:
class DelegateComparer<T> : IComparer<T>
{
public Func<T, T, int> CompareFunction { get; set; }
public DelegateComparer(Func<T, T, int> compareFunction)
{
CompareFunction = compareFunction;
}
public int Compare(T x, T y)
{
return CompareFunction(x, y);
}
}
And now i can define a nice extension method:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, TKey, int> compareFunction)
{
var comparer = new DelegateComparer<TKey>(compareFunction);
return source.OrderBy(keySelector, comparer);
}