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