I have some code that dynamically builds up some search criteria based on user input, resulting in an
Expression<Func<T, bool>> that is passed to the LINQ .Where() method. It works fine when input is present, but when input is not present, I want to create a simple 'return false;' statement so that no results are returned.
Below is my current attempt, but when this is passed to the .Where() method it throws a NotSupportedException "Unknown LINQ expression of type 'Block'."
var parameter = Expression.Parameter(typeof(T), "x"); var falseValue = Expression.Constant(false); var returnTarget = Expression.Label(typeof (bool)); var returnFalseExpression = Expression.Block(Expression.Return(returnTarget, falseValue), Expression.Label(returnTarget, falseValue)); var lambdaExpression = Expression.Lambda<Func<T, bool>>(returnFalseExpression, parameter);
How can I build a 'return false' expression that can be interpreted by LINQ?
Expression<Func<T, bool>> falsePredicate = x => false;
Can you wrap the entire thing in an if-else expression?
if input return <your normal code> else return false
The return is implicit in expressions; the return value of the expression will simply be the last value. So you could try:
Expression.Condition ( Expression.NotEqual(input, Expression.Constant("")), normalSearchExpression, Expression.Constant(false) )
normalSearchExpression also returns a bool.