Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use TrueForAll

Tags:

c#

list

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.

like image 660
Sturm Avatar asked Jul 27 '13 12:07

Sturm


People also ask

How to use TrueForAll c#?

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

How do you set a Boolean array to false?

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.


2 Answers

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.

like image 123
Tim Schmelter Avatar answered Sep 20 '22 15:09

Tim Schmelter


One way is: You can use All..

var result = list.All(x => x);

If all are true, result will be true.

like image 37
Simon Whitehead Avatar answered Sep 18 '22 15:09

Simon Whitehead