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

.net c# expression-trees linq


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?

7/29/2013 10:45:54 PM

Accepted Answer

Expression<Func<T, bool>> falsePredicate = x => false;
11/23/2012 10:33:05 AM

Popular Answer

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


if input
    return <your normal code>
    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.NotEqual(input, Expression.Constant("")), 

That's assuming normalSearchExpression also returns a bool.

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow