Monday, March 25, 2013

IOrderedQueryable<T> Extension Method (C#)

Here's a modified version of Nick Harrison's IOrderedQueryable extension method in his dynamic linq query post:
static class IQueryableExtensions  
     public static IOrderedQueryable<TSource> GenericEvaluateOrderBy<TSource>(this IQueryable<TSource> query, string propertyName)  
       var type = typeof(TSource);  
       var property = type.GetProperty(propertyName);  
       var parameter = Expression.Parameter(type, "p");  
       var propertyReference = Expression.Property(parameter, property); //p.ProductName  
       var sortExpression = Expression.Call(  
         new Type[] { type, property.PropertyType },  
         query.Expression, Expression.Quote(Expression.Lambda(Expression.MakeMemberAccess(parameter, property), parameter)));  
       return query.Provider.CreateQuery<TSource>(sortExpression) as IOrderedQueryable<TSource>;  
In order to use this, you could declare a IQueryable object similar to this:
 private void TestExtensionMethod()  
       IQueryable<Product> prodSorted = model.Products.AsQueryable();  
       Console.WriteLine("\nUsing GenericEvaluateOrderBy");  
       prodSorted = prodSorted.GenericEvaluateOrderBy("ProductName");  
       foreach (Product p in prodSorted)  
         Console.WriteLine("Product Name: " + p.ProductName + " Product Price:" + p.UnitPrice);  


Post a Comment