Skip to content

Instantly share code, notes, and snippets.

@richardkundl
Last active December 15, 2015 11:29
Show Gist options
  • Save richardkundl/5253349 to your computer and use it in GitHub Desktop.
Save richardkundl/5253349 to your computer and use it in GitHub Desktop.
Extending linq order by method.
namespace Common.Extension
{
using System.Linq;
using System.Linq.Expressions;
public static class GenericEvaulatingOrderBy
{
private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
{
var param = Expression.Parameter(typeof(T), "p");
var property = Expression.PropertyOrField(param, propertyName);
var sort = Expression.Lambda(property, param);
var call = Expression.Call(
typeof(Queryable),
(!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty),
new[] { typeof(T), property.Type },
source.Expression,
Expression.Quote(sort));
return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
}
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
{
return OrderingHelper(source, propertyName, false, false);
}
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName, bool descending)
{
return OrderingHelper(source, propertyName, descending, false);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName)
{
return OrderingHelper(source, propertyName, false, true);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName, bool descending)
{
return OrderingHelper(source, propertyName, descending, true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment