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

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations