简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM