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

JTew picture JTew · Nov 21, 2008 · Viewed 85.1k times · Source
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?

Answer

Aaron Powell picture Aaron Powell · Nov 21, 2008

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));