(Code below has been updated and worked properly)
There is dynamic OrderBy sample from LinqPad. What I want to do is just simply apply ‘Where’ rather than ‘OrderBy’ for this sample. Here is my code:
IQueryable query =
from p in Purchases
//where p.Price > 100
select p;
string propToWhere = "Price";
ParameterExpression purchaseParam = Expression.Parameter (typeof (Purchase), "p");
MemberExpression member = Expression.PropertyOrField (purchaseParam, propToWhere);
Expression<Func<Purchase, bool>> lambda = p => p.Price < 100;
lambda.ToString().Dump ("lambda.ToString");
//Type[] exprArgTypes = { query.ElementType, lambda.Body.Type };
Type[] exprArgTypes = { query.ElementType };
MethodCallExpression methodCall =
Expression.Call (typeof (Queryable), "Where", exprArgTypes, query.Expression, lambda);
IQueryable q = query.Provider.CreateQuery (methodCall);
q.Dump();
q.Expression.ToString().Dump("q.Expression");
This code gets exception:
“InvalidOperationException: No method ‘Where’ on type ‘System.Linq.Queryable’ is compatible with the supplied arguments.”
Any help is appraicated.
Cheers
Use the lambda that Jon Skeet supplied. Perhaps he can also explain why
ParameterExpressionis so painful to use and requires using the same instance, instead of being able to be matched by name 🙂Modify this line:
exprArgTypesis type parameters toAs you can see it only has one type parameter –
TSource, which isPurchase. What you were doing, effectively, was callingWheremethod with two type parameters like below:Once both of those fixes are in the expression runs with no problem.