Frequently I have encountered the requirement to implent sort on individual columns in a table. I thought that the easiest and most intutive way of implementing this in MVC controller was to express the column name as a string variable value. But after a couple of attempts I realised that the default Sort method of IQueryable interface in linq does not work and hence we need to add our own method to do this task.
Google search quickly returned some nice results, but in short something like this should work.
Google search quickly returned some nice results, but in short something like this should work.
private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
{
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 OrderingHelper(source, propertyName, false, false);
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
{
return OrderingHelper(source, propertyName, true, false);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName)
{
return OrderingHelper(source, propertyName, false, true);
}
public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string propertyName)
{
return OrderingHelper(source, propertyName, true, true);
}
More Links
No comments:
Post a Comment