【问题标题】:How to efficiently reduce list of booleans with AND / OR operators to single result如何使用 AND / OR 运算符有效地将布尔值列表减少为单个结果
【发布时间】:2019-11-18 07:26:38
【问题描述】:

我正在寻找一种有效的方法来减少包含 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?

【问题讨论】:

标签: c# boolean boolean-logic


【解决方案1】:

你说你已经拥有的简单迭代可能是最好的选择......但如果你真的喜欢一些 LINQ - Enumerable.Aggregate 是你正在寻找的方法。大致如下:

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

【讨论】:

  • [@Alexei Levenkov] 很棒的推荐!非常感谢您的快速响应,非常适合我到目前为止的使用方式。非常感谢。
猜你喜欢
  • 2021-11-06
  • 2015-11-18
  • 2013-06-06
  • 2017-03-23
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
相关资源
最近更新 更多