Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

10 Feb 2010

Another missing method for IEnumerable<T>

Currently there are two overloads for OrderBy on Enumerable

  • OrderBy(this IEnumerable source, Func<TSource, TKey> keySelector)
  • OrderBy(this IEnumerable source, Func<TSource, TKey> keySelector, IComparer comparer)

Because i don’t want to implement an IComparer 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);
}