use the following method if you want to be able to do something like this:
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
IEnumerable<Pet> query = pets.OrderBy("Age", true);
foreach (Pet pet in query)
{
Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
}
/*
This code produces the following output:
Whiskers - 1
Boots - 4
Barley - 8
*/
public
staticIOrderedEnumerable<T> OrderBy<T>(thisIEnumerable<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 MyLamda = Expression.Lambda(MyProperty, MyObject);
var MyMethod = Expression.Call(typeof(Enumerable), ascending ? "OrderBy" : "OrderByDescending", new[] { typeof(T), MyLamda.Body.Type }, MyEnumeratedObject, MyLamda);
var MySortedLamda = Expression.Lambda<Func<IEnumerable<T>, IOrderedEnumerable<T>>>(MyMethod, MyEnumeratedObject).Compile();
return MySortedLamda(items);
}