Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check a value in a boolean List?

I have this List: List<bool> values = new List<bool>();

Filled with: True,True,False,True,False,False,True

When I do this: int amountTrue = values.Count(v => true); it returns 7. That's just the amount of values in the List. I think it checks if the value exists, but this is not what I want.

How do I get the amount of True values in the List by using Count or any other chainable method? I know I can loop through it but I think this could be done easier.

like image 625
Starfish Avatar asked Dec 08 '22 01:12

Starfish


2 Answers

The Count method can take a predicate, which is basically a method that returns a boolean. In this case, the Count method is counting the number of items that "pass" the predicate. What you were doing is saying "for each item, check if true is true", which is, obviously, always true. What you want to do is check if each value is true, which you can do like so:

values.Count(v => v);

or longhand

values.Where(v => v).Count();
like image 151
Dave Zych Avatar answered Dec 10 '22 15:12

Dave Zych


List<bool> values = new List<bool>() { true, true, false, true, false, false, true };

Console.WriteLine(values.Count(v => v == true)); //output : 4
Console.WriteLine(values.Count(v => v == false)); //output : 3

//equivalent
Console.WriteLine(values.Count(v => v)); //v == true, output : 4
Console.WriteLine(values.Count(v => !v)); //v == false, output : 3

Console output :

4

3

4

3

like image 33
Gabriel Avatar answered Dec 10 '22 15:12

Gabriel