在功能阵列逻辑运算符 [英] Logical operator on array of functions
问题描述
我已经有这个想法了一段时间,我很好奇,如果有可能在一个值得方法来实现。我想利用布尔返回拉姆达前pressions的数组,并对其结果进行逻辑运算。这里是一个有效的列表的毫无意义的例子:
I've had this idea for a while, and I'm curious if it's possible to implement in a worthwhile way. I want to take an array of boolean-returning lambda expressions and perform logical operations on their results. Here's a pointless example of a valid list:
var tests = new List<Func<int, bool>>() {
(x) => x > 10,
(x) => x < 100,
(x) => x != 42
};
我想要做的本质上是
What I'd like to do is essentially
bool result = tests.And();
或执行其它逻辑运算。我知道我可以写一个IEnumerable,实现类和做到这一点,但如果它已经做了我想知道。很明显,实现具有以相同的方式,有效地工作,短路
or perform other logical operations. I realize I could write an IEnumerable-implementing class and do this, but I was wondering if it has already been done. Obviously, the implementation has to work efficiently, short-circuiting in the same way as
if (truthyExpression || falseyExpression)
将永远围绕得到评估 falseyEx pression
。
我的框架,也许可以有助于唯一看到的是的位阵列,但我不知道我怎么可以用,如果没有pre-评估每前pression,击败短cicuiting的实用性。
The only thing I see in the framework that could maybe be helpful is Bit Array, but I'm not sure how I could use that without pre-evaluating every expression, defeating the usefulness of short-cicuiting.
推荐答案
您可以使用内置的 Enumerable.Any
和 Enumerable.All
扩展方法。
You could use the built-in Enumerable.Any
and Enumerable.All
extension methods.
bool andResult = tests.All(test => test(value));
bool orResult = tests.Any(test => test(value));
这篇关于在功能阵列逻辑运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!