创建表达式<func <iqueryable <t>,IOrderedQueryable <t>&gt;&gt;?</t> </func <iqueryable <t>

时间:2013-12-16 09:13:36

标签: c# expression linq-expressions

我想创建一个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)的内容。

请您指导我如何做到这一点?

1 个答案:

答案 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);

TRegistrationDate表达式中selector属性的类型。

您可以使用MakeGenericType从参数类型中获取可查询类型:

Type argType = typeof(DateTime);
Type queryableType = typeof(IQueryable<>).MakeGenericType(argType);