How to check unknown number of booleans c#

110 Views Asked by At

I need to check unknown number of booleans.. depending on the result it will do the appropriate function. Here is example of what I'm searching:

if(bool[x] && bool[y] && bool[z] ...)
   myFunc();
5

There are 5 best solutions below

0
On BEST ANSWER

You can use LINQ for that.

If you need all the bools to be true, you can use Any:

if (bools.All(b => b))

If you need, for example, 4 of them exactly to be true, you can use Count:

if (bools.Count(b => b) == 4)

Or at least one, there's Any

if (bools.Any(b => b))
0
On

Something like this:

var all=true;
for (var i=x; i<z; i++) if (!bool[i]) {all=false; break;}
if (all) myFunc()

or, if x, y, z are not sequential, put them in the list or array:

int[] indices = new [] {x, y, z};

and then iterate like this:

var all=true;
foreach (var i in indices) if (!bool[i]) {all=false; break;}
if (all) myFunc()
0
On

You can use LINQ function All():

var all = bool.All(x=>x == true);
if(all)
    myFunc();

or simply

var all = bool.All(x=>x);
if(all)
    myFunc();
0
On
if (bool.Any(m => !m)
{
    // At least one bool is false
}
else
{
    // All bools are true
}
0
On

Use Linq to check that all the values meet the predicate.

if(bool.All())