3

我想在 BinaryExpression 中组合条件列表。问题是我希望所有条件都在同一级别,这样:

True == True And True == False And True == True And True == True And True == True Or True == False And True == True And True == True And True == True And True == True And真 == 真或真 == 真

但是生成了表达式:

(((((((((((((True == True) And (True == False)) And (True == True)) And (True == True)) And (True == True))) 或者(True == False)) And (True == True)) And (True == True)) And (True == True)) And (True == True)) And (True == True)) Or (True == 真))

var currentExpr = this.MakeExpression(list.First());
foreach (bool obj in list.Skip(1))
{
    var nextExpr = this.MakeExpression(obj);
    switch (type)
    {
        case 1: // And
            currentExpr = Expression.And(currentExpr, nextExpr);
            break;
        case 2: // Or
            currentExpr = Expression.Or(currentExpr, nextExpr);
            break;
    }
}


private BinaryExpression MakeExpression(bool value)
{
    BinaryExpression expression = Expression.Equal(Expression.Constant(true),Expression.Constant(value));
    return expression;
}
4

1 回答 1

0

OR您可以通过自己延迟 s来处理优先级:

var andExprs = new List<BinaryExpression>();
andExprs.Add(this.MakeExpression(list.First()));
foreach (bool obj in list.Skip(1))
{
    var nextExpr = this.MakeExpression(obj);
    switch (type)
    {
        case 1: // And
            andExprs[andExprs.Count-1] = Expression.And(andExprs[andExprs.Count-1], nextExpr);
            break;
        case 2: // Or
            andExprs.Add(nextExpr);
            break;
    }
}

var currentExpr = andExprs.First();
foreach (var expr in andExprs.Skip(1))
{
    currentExpr = Expression.Or(currentExpr, expr);
}

我现在无法测试代码,因此可能存在拼写错误(是否andExprs.Count需要andExprs.Count()?),但这应该会给你一个大致的想法。

于 2013-10-23T23:39:30.023 回答