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

.net, c#, expression-trees, linq

Solution

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

Problem

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?

Original source