Two expressions of combination (expression
type expressions with logical operators (such as AND, OR, or NOT).
Solution
To use the two expressions of logical operators, you can choose the following methods:<code>Expression<func bool="">> expr1; Expression<func bool="">> expr2; ... // 这不会按预期工作 Expression<func bool="">> andExpression = expr1 AND expr2;</code>
If you use the same parameterexpression in EXPR1 and Expr2, you can simply combine their text and use the original parameter to create a new Lambda expression.
<code>var body = Expression.AndAlso(expr1.Body, expr2.Body); var lambda = Expression.Lambda<func bool="">(body, expr1.Parameters[0]);</code>
If two expressions use different ParameterexPression instances, according to your Linq provider, you can use Invoke to combine them:
<code>static Expression<func bool=""> Not<T>( this Expression<func bool=""> expr) { return Expression.Lambda<func bool="">( Expression.Not(expr.Body), expr.Parameters[0]); }</code>
Method 3: General Version
<code>static Expression<func bool=""> AndAlso<T>( this Expression<func bool=""> left, Expression<func bool=""> right) { var param = Expression.Parameter(typeof(T), "x"); var body = Expression.AndAlso( Expression.Invoke(left, param), Expression.Invoke(right, param) ); var lambda = Expression.Lambda<func bool="">(body, param); return lambda; }</code>
This version will automatically detect whether the two expressions use the same parameters and adjust the expression accordingly:
For .NET 4.0 and higher versions, you can use the ExpressionVisitor class to create an EF security expression. This method allows you to replace the original parameter with the number of new parameters without explicit conversion:
<code>static Expression<func bool=""> AndAlso<T>( this Expression<func bool=""> expr1, Expression<func bool=""> expr2) { // 检测相同的参数 ParameterExpression param = expr1.Parameters[0]; if (ReferenceEquals(param, expr2.Parameters[0])) { return Expression.Lambda<func bool="">( Expression.AndAlso(expr1.Body, expr2.Body), param); } // 否则,使用 Invoke 来组合 return Expression.Lambda<func bool="">( Expression.AndAlso( expr1.Body, Expression.Invoke(expr2, param)), param); }</code>
The above is the detailed content of How to Combine Two Expression Expressions Using Logical Operators?. For more information, please follow other related articles on the PHP Chinese website!