我有一个 dictinary
的 bool
和 string
包含一个操作,我想以递归方式获取输出如何实现。
IDictionary<bool , string> lstIfResult = null;
假设这个列表包含:
{
{ true, "AND" },
{ false, "OR" },
{ true, "AND" }
}
我的代码是:
for (int i = 0; i < lstIfResult.Count(); i++)
{
bool res = getBinaryOprResult(lstIfResult.ElementAt(i) , lstIfResult.ElementAt(i + 1));
}
private static bool getBinaryOprResult(KeyValuePair<bool, string> firstIfResult,
KeyValuePair<bool, string> secondIfResult)
{
switch (firstIfResult.Value)
{
case "AND":
return firstIfResult.Key && secondIfResult.Key;
case "OR":
return firstIfResult.Key || secondIfResult.Key;
default:
return false;
}
}
我如何递归此函数以使关键元素 1 等同于 2,然后它们的结果等同于第三个。 在 1 和 2 之间使用的操作是第一个,在它们的输出到第三个之间使用的操作是第二个。最后的关键元素操作将被忽略。 提前致谢。
最佳答案
首先,让我们提取模型(给定一个名称,例如“OR”
,我们返回一个要执行的操作):
private static Dictionary<string, Func<bool, bool, bool>> s_Operations =
new Dictionary<string, Func<bool, bool, bool>>(StringComparer.OrdinalIgnoreCase) {
{ "AND", (a, b) => a && b},
{ "OR", (a, b) => a || b},
{ "XOR", (a, b) => a ^ b },
{ "TRUE", (a, b) => true },
{"FALSE", (a, b) => false },
//TODO: add more operations, synonyms etc.
};
然后您可以在 Linq 的帮助下进行聚合
(注意,最后一个运算 - “OR”
将被忽略):
using System.Linq;
...
// I've created list, but any collection which implements
// IEnumerable<KeyValuePair<bool, string>> will do
IEnumerable<KeyValuePair<bool, string>> list = new List<KeyValuePair<bool, string>>() {
new KeyValuePair<bool, string>( true, "AND"),
new KeyValuePair<bool, string>(false, "OR"),
new KeyValuePair<bool, string>( true, "OR"),
};
...
// ((true && false) || true) == true
bool result = list
.Aggregate((s, a) => new KeyValuePair<bool, string>(
s_Operations[s.Value](s.Key, a.Key),
a.Value))
.Key;
关于c# - 如何在递归中一起执行 bool 表达式列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218830/