I have 3 predicates, I'd like make an AndAlso
between. I found several sample on the board, but can't solve my problem.
These predicates are : Expression<Func<T, bool>>
I have this code :
Expression<Func<T, bool>> predicate1 = ......;
Expression<Func<T, bool>> predicate2 = ......;
Expression<Func<T, bool>> predicate3 = ......;
I create an extension method to make an "AndAlso" :
public static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr,
Expression<Func<T, bool>> exprAdd)
{
var param = Expression.Parameter(typeof(T), "p");
var predicateBody = Expression.AndAlso(expr.Body, exprAdd.Body);
return Expression.Lambda<Func<T, bool>>(predicateBody, param);
//Tried this too
//var body = Expression.AndAlso(expr.Body, exprAdd.Body);
//return Expression.Lambda<Func<T, bool>>(body, expr.Parameters[0]);
}
I use like this :
var finalPredicate = predicate1
.AndAlso<MyClass>(predicate2)
.AndAlso<MyClass>(predicate3);
The predicate look this :
When I use in a query :
var res = myListAsQueryable().Where(finalPredicate).ToList<MyClass>();
I get this error : variable 'p' of type 'BuilderPredicate.MyClass' referenced from scope '', but it is not defined
Could you tell me what's wrong ?
Thanks a lot,
The problem is creating a new parameter - you can do that, but if you simply assign it to the final lambda, there's no connection between your parameter and the original parameters in the provided expressions. Try changing param names of the expressions and then check the
finalPredicate
. You will see something like:The problem should be obvious now.
Marc Gravell suggest in this answer a general
Expression.AndAlso
, which is exactly what you need:(code by Marc, not me)