Skip to content

Instantly share code, notes, and snippets.

@thomascristanis
Created March 12, 2015 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomascristanis/3a851850a8927d7d090e to your computer and use it in GitHub Desktop.
Save thomascristanis/3a851850a8927d7d090e to your computer and use it in GitHub Desktop.
public static IQueryable<TEntity> OrderBy<TEntity>(IQueryable<TEntity> source, string orderByProperty, bool desc)
{
string command = desc ? "OrderByDescending" : "OrderBy";
var type = typeof(TEntity);
var property = type.GetProperty(orderByProperty);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
source.Expression, Expression.Quote(orderByExpression));
return source.Provider.CreateQuery<TEntity>(resultExpression);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment