Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply OrderBy on an IQueryable using a string column name within a generic extension method?

public static IQueryable<TResult> ApplySortFilter<T, TResult>(this IQueryable<T> query, string columnName)
  where T : EntityObject
{
  var param = Expression.Parameter(typeof(T), "o");
  var body = Expression.PropertyOrField(param,columnName);

  var sortExpression = Expression.Lambda(body, param);
  return query.OrderBy(sortExpression);
}

Because the type for OrderBy is not inferred from sortExpression I need to specify it something like this at run time:

var sortExpression = Expression.Lambda<T, TSortColumn>(body, param);

Or

return query.OrderBy<T, TSortColumn>(sortExpression);

I don't think this is possible however as TSortColumn can only be determined during runtime.

Is there a way around this?

like image 500
JTew Avatar asked Nov 21 '08 01:11

JTew


2 Answers

We did something similar (not 100% the same, but similar) in a LINQ to SQL project. Here's the code:

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) {
    var type = typeof(T);
    var property = type.GetProperty(ordering);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExp = Expression.Lambda(propertyAccess, parameter);
    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
    return source.Provider.CreateQuery<T>(resultExp);
}

We didn't actually use a generic, we had a known class, but it should work on a generic (I've put the generic placeholder where it should be).

Edit: For descending order, pass in OrderByDescending instead of "OrderBy":

MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
like image 54
Aaron Powell Avatar answered Oct 31 '22 11:10

Aaron Powell


You can also use Dynamic Linq

Info here http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

C# download here http://msdn.microsoft.com/en-us/vcsharp/bb894665.aspx

Then just add the using Linq.Dynamic; and you automatically get 2 additional extension methods that can be used like this

return query.OrderBy("StringColumnName");
like image 32
Jeremy Coenen Avatar answered Oct 31 '22 10:10

Jeremy Coenen