Consider this:
var propertyinfo = typeof(Customer).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;
now I want to declare
Func<int,orderType>
I know its not possible directly since ordertype
is at runtime but is there is any workaround ?
this is exactly what I want to do :
var propertyinfo = typeof(T).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;
var param = Expression.Parameter(typeof(T), "x");
var sortExpression = (Expression.Lambda<Func<T, orderType>>
(Expression.Convert(Expression.Property(param, sortExpressionStr), typeof(orderType)), param));
all this because I want to convert:
Expression<Func<T,object>> to Expression<Func<T,orderType>>
or if its not possible then I want to create it from the first place with the right type , the case is as following:
I'm inside a method which have a type(Customer)
and a property name of that type I want to order by it , I want to create a sort expression tree to pass it to Orderby
(here).
You can do this by using an open generic type definition, and then making the specific type from that:
However, what you're trying to do (calling
Lambda<TDelegate>
) is not directly possible. You must callLambda
without a type parameter:This will create the proper
Func<,>
for you behind the scenes. If you want to compile the expression and use the delegate, you can only do this dynamically withIf you want to call the
OrderBy
extension method onQueryable
, things get a little more complicated:You can use the Type.MakeGenericType Method:
This should work:
From here.
See if my solution dynamic enough.
Base on above, it's not difficult to change
Product
toT
to make it generic.You want to use Dynamic Linq, a part of the Visual Studio sample code.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
this worked my problem was i used to pass extra parameter Typeof(Object) and orderby used to tell me it cant sort by Object type. thanks all
thanks dtb i will check if your answer work too and i will accept it if it works if not i will accept thsi one.
You can get the
Type
associated withFunc<int,orderType>
in case you wanted to e.g. pass it into CreateDelegate.But what are you ultimately wanting to do with it? There may be a more straightforward approach.