I wanna create an Expression<Func<IQueryable<T>, IOrderedQueryable<T>>>
, I have the following codes :
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);
I'm gonna create c => c.OrderBy(q => q.RegistrationDate)
or c => c.OrderByDescending(q => q.RegistrationDate)
or generally something like c => c.OrderByDescending(q => q.RegistrationDate).ThenBy(q=>q.Name)
from above codes.
Could you please guide how I can do it?
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);
Where T
is the type with the RegistrationDate
property in your selector
expression.
You can get the queryable type from the argument type using MakeGenericType
:
Type argType = typeof(DateTime);
Type queryableType = typeof(IQueryable<>).MakeGenericType(argType);