I have a list of bools and I want to check if every one is set to true. I can run a loop and check it that way but I want to try to do it with TrueForAll
method of a list. I need a predicate for that but I couldn't find a clear example for such a simple task as this.
TrueForAll() Method. This method is used to determine whether every element in the array matches the conditions defined by the specified predicate. Syntax: public static bool TrueForAll (T[] array, Predicate<T> match);
An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays. fill() method in such cases.
Use All
:
bool alltrue = listOfBools.All(b => b);
It will return false
one the first false
.
However, since you are actually using a List<bool>
you can also use List.TrueForAll
in the similar way:
bool alltrue = listOfBools.TrueForAll(b => b);
But since that is limited to a list i would prefer Enumerable.All
.
One way is: You can use All
..
var result = list.All(x => x);
If all are true
, result
will be true
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With