如何使用AND / OR运算符有效地将布尔值列表简化为单个结果

时间:2019-07-08 18:31:54

标签: c# boolean boolean-logic

我正在寻找一种有效的方法来减少包含C#的AND / OR条件的True / False语句的列表。

考虑遍历每个项目,并通过一个简单的方程(例如,示例:

)简单地将每个项目评估为列表中的下一个协调项目。
if (item[1].operator == "AND") // Evaluate NEXT item's operator (AND/OR)
{  
   result == item[0] && item[1]  // Which would resolve out to T 
}
else if (item[1].operator == "OR")
{

}

*但是我必须包含在比较项目列表时还包括AND / OR操作的逻辑...

我需要将其简化为单个T / F结果的数据示例。 我有一个布尔值和运算符(AND / OR)的列表,需要找到一种方法

public class TestProcessor() {
    bool Result { get; set; }
    string Operator { get; set; }  // Specifies if it is tied together in the statement with an AND or an OR 
...
}


public class TestLogic() {
    List<TestProcessor> TestProcesses { get; set; }

    public bool ReduceAll() {
     ...  This would essentially take all items in the 'TestProcessor' property and resolve out the list of items accordingly in the order they are in from the list and in conjunction to if they are linked together with an AND or an OR
    }
}


If I had a list of Processes that Result in 
* Note:  (First item and last item don't need AND/OR operators)
[0]  Result = True,  Operator = null    
[1]  Result = True,  Operator = OR   
[2]  Result = True,  Operator = OR   
[3]  Result = True,  Operator = AND   
[4]  Result = False,  Operator = OR
[5]  Result = True,  Operator = AND      

(T) OR (T) OR (T) AND (T) OR (F) AND (T)  which would resolve out to: True 

Is there an easy way or a more dynamic way to do this?  Or is there a way to more easily just pass the data to the compiler to evaluate out the entire list of items for it to evaluate without all the extra effort?

1 个答案:

答案 0 :(得分:1)

您说您已经拥有的简单迭代可能是最好的选择……但是,如果您真的喜欢LINQ,那么您会寻找Enumerable.Aggregate。大致像:

var result = list.Aggregate(true, (sum, cur) => 
      cur.Operator == "AND" ? sum && cur.Result : sum || cur.Result);