Created
October 30, 2013 23:31
-
-
Save danielmackay/7242112 to your computer and use it in GitHub Desktop.
Generic sorting method. #EF, #LINQ.
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
public static class QueryableExt | |
{ | |
public static IOrderedQueryable<T> OrderBy<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel = false) | |
{ | |
ParameterExpression param = Expression.Parameter(typeof(T), string.Empty); // I don't care about some naming | |
MemberExpression property = Expression.PropertyOrField(param, propertyName); | |
LambdaExpression sort = Expression.Lambda(property, param); | |
MethodCallExpression 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 OrderBy(source, propertyName, false, false); | |
} | |
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName) | |
{ | |
return OrderBy(source, propertyName, true, false); | |
} | |
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName) | |
{ | |
return OrderBy(source, propertyName, false, true); | |
} | |
public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string propertyName) | |
{ | |
return OrderBy(source, propertyName, true, true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment