It irritated me that LINQ gives me an OrderBy that takes a class implementing IComparer as an argument, but does not support passing in a simple anonymous comparer function. I rectified that.
This class creates an IComparer from your comparer function...
///
/// Creates an instance for the given
/// delegate function.
///
internal class ComparerFactory : IComparer
{
public static IComparer Create(Func comparison)
{
return new ComparerFactory(comparison);
}
private readonly Func _comparison;
private ComparerFactory(Func comparison)
{
_comparison = comparison;
}
#region IComparer Members
public int Compare(T x, T y)
{
return _comparison(x, y);
}
#endregion
}
...and these extension methods expose my new OrderBy overloads on enumerables. I doubt this works for LINQ to SQL, but it's great for LINQ to Objects.
public static class EnumerableExtensions
{
///
/// Sorts the elements of a sequence in ascending order by using a specified comparison delegate.
///
public static IOrderedEnumerable OrderBy(this IEnumerable source, Func keySelector,
Func comparison)
{
var comparer = ComparerFactory.Create(comparison);
return source.OrderBy(keySelector, comparer);
}
///
/// Sorts the elements of a sequence in descending order by using a specified comparison delegate.
///
public static IOrderedEnumerable OrderByDescending(this IEnumerable source, Func keySelector,
Func comparison)
{
var comparer = ComparerFactory.Create(comparison);
return source.OrderByDescending(keySelector, comparer);
}
}
You're welcome to put this on codeplex if you like.