Eric Anastas
Eric Anastas

Reputation: 22213

What is the most efficent way to perform boolean logic operations in C#.NET?

I'm writing a plugin for another piece of sofware we use in my office that will allow users to audit the files they are working on. I'm trying to keep my tool as flexible as possible. The idea I have is that the user will generate a tree of Nodes that can contain other Nodes as sub-nodes. At the bottom of the tree the Nodes will be condition nodes that will either fail or pass depending on the file the user is working in. In addition, the user can set each Node to a specific logic 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 

What I'm trying to figure out now is if I have some collection of bool's that were returned by a node or sub-node, what is the most efficient way to apply the logic types above to this list? Off hand I started writing foreach statments, but it seems since binary logic is so fundamental to the way computers work there would be a better, faster, and less iterative method.

Upvotes: 3

Views: 167

Answers (1)

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29632

Linq 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);

This really still just does a foreach, but they are a lot more compact and the All and Any operations fit what you need.

The p => p is a lambda that returns a boolean. If you for example are checking nodes that have a method DoesThisPass, you rewrite the checks like this:

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());

Upvotes: 5

Related Questions