1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public static class QueryableExtensions
{
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortCriteria)
{
return source.AddSort(sortCriteria, _orderBy);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string sortCriteria)
{
return source.AddSort(sortCriteria, _thenBy);
}
private static readonly MethodInfo _orderBy = typeof(Queryable)
.GetMethods()
.Where(m => m.Name == "OrderBy" && m.GetParameters().Length == 2)
.First();
private static readonly MethodInfo _thenBy = typeof(Queryable)
.GetMethods()
.Where(m => m.Name == "ThenBy" && m.GetParameters().Length == 2)
.First();
private static IOrderedQueryable<T> AddSort<T>(this IQueryable<T> source, string sortCriteria, MethodInfo orderMethod)
{
Type criteriaType;
var expr = MakeSelectorExpression<T>(sortCriteria, out criteriaType);
var realMethod = orderMethod.MakeGenericMethod(typeof(T), criteriaType);
return (IOrderedQueryable<T>)realMethod.Invoke(null, new object[] { source, expr });
}
static LambdaExpression MakeSelectorExpression<T>(string propertyName, out Type propertyType)
{
var param = Expression.Parameter(typeof(T));
var body = Expression.Property(param, propertyName);
var expr = Expression.Lambda(body, param);
propertyType = body.Type;
return expr;
}
} |
Partager