我需要动态创建表达式。我的问题是如何在System.Linq.Expression中添加括号以处理优先级...

int a = 1, b = 1, c = 1, d = 2;

我已将以下表达式转换为

 var v = a > 1 || b > 1 && c > 1 || d > 1;
 Expression case1Expr =

                Expression.AndAlso(
                Expression.OrElse(
                Expression.GreaterThan(Expression.Parameter(typeof(int), "a"), Expression.Constant(1)),
                Expression.GreaterThan(Expression.Parameter(typeof(int), "b"), Expression.Constant(1))),


                Expression.OrElse(
                Expression.GreaterThan(Expression.Parameter(typeof(int), "c"), Expression.Constant(1)),
                Expression.GreaterThan(Expression.Parameter(typeof(int), "d"), Expression.Constant(1))));


但是如何用括号将其转换,

var v2 = (a > 1 || b > 1) && (c > 1 || d > 1);

最佳答案

我可能会遗漏您的问题,但您不会这样做:

Expression first = Expression.OrElse(
    Expression.GreaterThan(Expression.Parameter(typeof(int), "a"), Expression.Constant(1)),
    Expression.GreaterThan(Expression.Parameter(typeof(int), "b"), Expression.Constant(1)));

Expression second = Expression.OrElse(
    Expression.GreaterThan(Expression.Parameter(typeof(int), "c"), Expression.Constant(1)),
    Expression.GreaterThan(Expression.Parameter(typeof(int), "d"), Expression.Constant(1)));

Expression final = Expression.AndAlso(first, second);


结果:(((a > 1) OrElse (b > 1)) AndAlso ((c > 1) OrElse (d > 1)))

09-10 00:48