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);
}

This entry was posted on Wednesday, February 10th, 2010 at 19:29 and is filed under C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply