How can I create a LINQ-friendly 'return false' expression using C# expression trees?

.net c# expression-trees linq

Question

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?

Accepted Answer

Expression<Func<T, bool>> falsePredicate = x => false;

Popular Answer

Can you wrap the entire thing in an if-else expression?

Meaning:

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)
    )

That's assuming normalSearchExpression also returns a bool.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why