Skip to content

Instantly share code, notes, and snippets.

@foyzulkarim
Last active December 21, 2015 15:00
Show Gist options
  • Save foyzulkarim/d09aa9f0d0784316f8c1 to your computer and use it in GitHub Desktop.
Save foyzulkarim/d09aa9f0d0784316f8c1 to your computer and use it in GitHub Desktop.
Problem scenario:
private static Func<IQueryable<TSource>, IOrderedQueryable<TSource>> OrderByFunc<TSource>(string propertyName, bool ascending = true)
{
var source = Expression.Parameter(typeof(IQueryable<TSource>), "source");
var item = Expression.Parameter(typeof(TSource), "item");
var member = Expression.Property(item, propertyName);
var selector = Expression.Quote(Expression.Lambda(member, item));
var body = Expression.Call(
typeof(Queryable), ascending ? "OrderBy" : "OrderByDescending",
new Type[] { item.Type, member.Type },
source, selector);
var expr = Expression.Lambda<Func<IQueryable<TSource>, IOrderedQueryable<TSource>>>(body, source);
var func = expr.Compile();
return func;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment