Donate

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(  
         typeof(Queryable),  
         "OrderBy",  
         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);  
       }  
 }  

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input