我想创建一个Expression<Func<IQueryable<T>, IOrderedQueryable<T>>>
,我有以下代码:
Expression selector = q => q.RegistrationDate
MethodInfo orderByMethodInfo = typeof(Queryable).GetMethods().First(method => method.Name == "OrderBy" && method.GetParameters().Count() == 2).MakeGenericMethod(argumentTypes);
MethodInfo orderByDescMethodInfo = typeof(Queryable).GetMethods().First(method => method.Name == "OrderByDescending" && method.GetParameters().Count() == 2).MakeGenericMethod(argumentTypes);
我将从上面的代码中创建c => c.OrderBy(q => q.RegistrationDate)
或c => c.OrderByDescending(q => q.RegistrationDate)
或类似c => c.OrderByDescending(q => q.RegistrationDate).ThenBy(q=>q.Name)
的内容。
请您指导我如何做到这一点?
答案 0 :(得分:2)
var paramExpr = Expression.Parameter(typeof(IQueryable<T>))
var orderByExpr = Expression.Call(orderByMethodInfo, paramExpr, selector);
var expr = Expression.Lambda<Func<IQueryable<T>, IOrderedQueryable<T>>>(orderByExpr, paramExpr);
T
是RegistrationDate
表达式中selector
属性的类型。
您可以使用MakeGenericType
从参数类型中获取可查询类型:
Type argType = typeof(DateTime);
Type queryableType = typeof(IQueryable<>).MakeGenericType(argType);