Public · Protected · Private
Expression Trees
Type: Public  |  Created: 2012-08-29  |  Frozen: Yes
« Previous Public Blog Next Public Blog »
Comments
  • // 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();


     

    2012-08-29 13:45
This blog is frozen. No new comments or edits allowed.