What is the most efficient way to perform logical operations in C # .NET?

I am writing a plugin for another piece of software that we use in my office that will allow users to check the files they are working on. I try to make my tool as flexible as possible. The idea I have is that the user will generate a tree of nodes that may contain other nodes as sub-nodes. At the bottom of the tree, nodes will be state nodes that either fail or skip depending on the file in which the user is working. In addition, the user can set each Node to a specific logical type, including AND, OR, NOR, NAND.

AND:  All sub nodes must pass 
OR:   At least one sub node must pass 
NAND: At least one sub node must fail
NOR:  All sub nodes must fail 

Now I'm trying to find out if I have a bool collection that was returned by Node or sub foreach, but it seems that since the binary logic is so fundamental that it works on a computer, there would be a faster, faster, and less iterative method.

+3
source share
1 answer

Link is your friend:

var booleans = new List<bool> { true, true, false, true };

bool allPass = booleans.All(p => p);
bool anyPass = booleans.Any(p => p);
bool allFail = booleans.All(p => !p);
bool anyFail = booleans.Any(p => !p);

In fact, it is just foreach, but they are much smaller, and the operations Alland Anyin line with what you need.

p => pis a lambda that returns a boolean. If you, for example, check the nodes that have a method DoesThisPass, you rewrite these checks as follows:

bool allPass = nodes.All(p => p.DoesThisPass());
bool anyPass = nodes.Any(p => p.DoesThisPass());
bool allFail = nodes.All(p => !p.DoesThisPass());
bool anyFail = nodes.Any(p => !p.DoesThisPass());
+5
source

Source: https://habr.com/ru/post/1773411/


All Articles