Home >Backend Development >C++ >How to Combine Logical Expressions in C# Expression?
When you have two
type expressions, you may need to use logical operators (such as AND, OR, or not) to combine them. This article discusses various methods to achieve this goal.
Expression<Func<bool>>
The same parameter instance
If the two expressions use the same , the combination is simple:
ParameterExpression
This is also applicable to negating a single operation:
<code class="language-csharp">var body = Expression.AndAlso(expr1.Body, expr2.Body); var lambda = Expression.Lambda<Func<bool>>(body, expr1.Parameters[0]);</code>
Different parameter examples
<code class="language-csharp">static Expression<Func<bool>> Not<T>( this Expression<Func<bool>> expr) { return Expression.Lambda<Func<bool>>( Expression.Not(expr.Body), expr.Parameters[0]); }</code>
If the expression uses different parameter instances, you can use to combine:
This method is also applicable to Invoke
and
<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>
General method OrElse
Not
From the .NET 4.0,
<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>provided a mechanism to build an EF compatible expression:
By selecting a method that is consistent with your specific scene, you can effectively combine the logical expression in the
instance.The above is the detailed content of How to Combine Logical Expressions in C# Expression?. For more information, please follow other related articles on the PHP Chinese website!