Last active
December 15, 2015 11:29
-
-
Save richardkundl/5253349 to your computer and use it in GitHub Desktop.
Extending linq order by method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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