Reputation: 3574
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.
Upvotes: 4
Views: 6224
Reputation: 762
values.Count(v => v); returns result according to value of v values.Count(v => true); always return true.
Upvotes: 0
Reputation: 333
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
nbTrue++;
nbFalse++;
Upvotes: 0
Reputation: 333
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
Upvotes: 4
Reputation: 21887
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();
Upvotes: 11