I found some really sexy code today. It was written by “mazzy maxim” as Community Content to MSDN.
What it does is to extend the OrderBy method for IEnumerables. You provide the name of the property you want to sort by, and the sort order. Without further ado, here’s the code:
public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> items, string property, bool ascending)
{
var MyObject = Expression.Parameter(typeof(T), "MyObject");
var MyEnumeratedObject = Expression.Parameter(typeof(IEnumerable<T>), "MyEnumeratedObject");
var MyProperty = Expression.Property(MyObject, property);
var MyLambda = Expression.Lambda(MyProperty, MyObject);
var MyMethod = Expression.Call(typeof(Enumerable),
ascending ? "OrderBy" : "OrderByDescending",
new[] { typeof(T), MyLambda.Body.Type },
MyEnumeratedObject,
MyLambda);
var MySortedLambda = Expression.Lambda<Func<IEnumerable<T>, IOrderedEnumerable<T>>>(MyMethod, MyEnumeratedObject).Compile();
return MySortedLambda(items);
}
So what we have is a generic extension method for IEnumerables that creates a lambda expression on the fly to sort the objects by the property with the given name.
Pretty cool or what?