How do I check a value in a boolean List?

+4 votes
asked Sep 9, 2015 by patrick2607

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.

5 Answers

+10 votes
answered Sep 9, 2015 by dave-zych

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();
+4 votes
answered Sep 9, 2015 by gab
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

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

Console output :





0 votes
answered Sep 10, 2015 by gab

A list of boolean doesn't contain relevant data such as keys or values for other queries, you might just want to use an alternative solution like incrementing integers. With your current solution, the list solution, when the list will grow over thousands of values it will take more cpu time to count all the elements and more memory to store all the elements.

Alternative solution :

int nbTrue = 0; // choose a significant name
int nbFalse = 0; // choose a significant name

0 votes
answered Sep 10, 2015 by grimcoder

var count = values.Count(v => true == v)

0 votes
answered Sep 10, 2015 by flyfrog

values.Count(v => v); returns result according to value of v values.Count(v => true); always return true.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter