Created
October 2, 2012 12:21
-
-
Save alfeg/3818602 to your computer and use it in GitHub Desktop.
SortBy
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 IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName) | |
{ | |
propertyName = propertyName.Trim(); | |
if (source == null) | |
{ | |
throw new ArgumentNullException("source"); | |
} | |
// DataSource control passes the sort parameter with a direction | |
// if the direction is descending | |
int descIndex = propertyName.IndexOf(" DESC"); | |
if (descIndex >= 0) | |
{ | |
propertyName = propertyName.Substring(0, descIndex).Trim(); | |
} | |
if (String.IsNullOrEmpty(propertyName)) | |
{ | |
return source; | |
} | |
return source.SortBy(propertyName, descIndex > 0); | |
} | |
public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName, bool descending) | |
{ | |
propertyName = propertyName.Trim(); | |
if (source == null) | |
{ | |
throw new ArgumentNullException("source"); | |
} | |
if (String.IsNullOrEmpty(propertyName)) | |
{ | |
return source; | |
} | |
ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty); | |
MemberExpression property = Expression.Property(parameter, propertyName); | |
LambdaExpression lambda = Expression.Lambda(property, parameter); | |
string methodName = (!descending) ? "OrderBy" : "OrderByDescending"; | |
Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName, | |
new Type[] { source.ElementType, property.Type }, | |
source.Expression, Expression.Quote(lambda)); | |
return source.Provider.CreateQuery<T>(methodCallExpression); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment