Expression Trees
// for a given class as below..
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
// Let us do sorting with expression
List<Person> persons = new List<Person>();
persons.Add(new Person{FirstName = "Ace",LastName = "the",Age = 24};);
persons.Add(new Person{FirstName = "Technical",LastName = "Interview",Age = 23};);
persons.Add(new Person{FirstName = "core",LastName = "Bore",Age = 22};3);
string sortByProp = "Age";
Type sortByPropType = typeof(Person).GetProperty(sortByProp).PropertyType;
ParameterExpression pe = Expression.Parameter(typeof(Person), "p");
Expression<Func<Person, int>> expr =
Expression.Lambda<Func<Person, int>>
(Expression.Property(pe, sortByProp), pe);
IQueryable<Person> query = persons.AsQueryable();
MethodInfo orderByMethodInfo = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(mi => mi.Name == "OrderBy"
&& mi.IsGenericMethodDefinition
&& mi.GetGenericArguments().Length == 2
&& mi.GetParameters().Length == 2);
List<Person> sortedList = (orderByMethodInfo.MakeGenericMethod(new Type[] { typeof(Person), sortByPropType }).Invoke(query,
new object[] { query, expr }) as
IOrderedQueryable<Person>).ToList();