I have two expressions of type Expression<Func<T, bool>> and I want to take to OR, AND or NOT of these and get a new expression of the same type
Expression<Func<T, bool>> expr1; Expression<Func<T, bool>> expr2; ... //how to do this (the code below will obviously not work) Expression<Func<T, bool>> andExpression = expr AND expr2
Well, you can use
Expression.AndAlso/OrElseetc to combine logical expressions, but the problem is the parameters; are you working with the sameParameterExpressionin expr1 and expr2? If so, it is easier:This also works well to negate a single operation:
Otherwise, depending on the LINQ provider, you might be able to combine them with
Invoke:Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for
Invoke, but it is quite lengthy (and I can’t remember where I left it…)Generalized version that picks the simplest route:
Starting from .NET 4.0, there is the
ExpressionVisitorclass which allows you to build expressions that are EF safe.