Home >Backend Development >C++ >How to Combine Logical Expressions of Type `Expression` in LINQ?
Expression<Func<bool>>
LINQ often uses expression, the expression is a representation of Lambda expression. When processing expressions, two logical expressions are often required, such as AND, OR, or Not.
We may want to combine these expressions to obtain the same type of new expression:
<code class="language-csharp">Expression<Func<bool>> expr1; Expression<Func<bool>> expr2;</code>
The expression of the combination with the same parameters
<code class="language-csharp">// 示例用法(原样无效) Expression<Func<bool>> andExpression = expr1 AND expr2;</code>
If and use the same parameters, the operation is very simple:
The expression of different parameters with a combination expr1
expr2
<code class="language-csharp">var body = Expression.AndAlso(expr1.Body, expr2.Body); var lambda = Expression.Lambda<Func<bool>>(body, expr1.Parameters[0]);</code>
General method
The following code fragment provides a common method to determine the most suitable way to determine the combination expression: Invoke
<code class="language-csharp">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>Other precautions
In .NET 4.0 and higher versions, you can use
Class to create EF security expressions:
<code class="language-csharp">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); } return Expression.Lambda<Func<bool>>( Expression.AndAlso( expr1.Body, Expression.Invoke(expr2, param)), param); }</code>This Revied Output Maintains The Original Image and Provides a More Concise and Readable Explanation of the Code Snippets. TED for Better Readability.
The above is the detailed content of How to Combine Logical Expressions of Type `Expression` in LINQ?. For more information, please follow other related articles on the PHP Chinese website!