How to check for unknown number of booleans C #

I need to check for an unknown number of gates. Depending on the result, it will perform the corresponding function. Here's an example of what I'm looking for:

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

      

+3


source to share


5 answers


You can use LINQ

for this.

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

:

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

      

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

:



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

      

Or at least one Any

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

      

+4


source


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

      

+1


source


Something like that:

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

      

or, if x, y, z

not sequential, put them in a list or array:

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

      

and then repeat like this:

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

      

0


source


if (bool.Any(m => !m)
{
    // At least one bool is false
}
else
{
    // All bools are true
}

      

0


source


Use Linq to check if all values ​​match the predicate.

if(bool.All())

0


source







All Articles