In my C# code, I have a list of type CustomClass
. This class contains a boolean property trueOrFalse
.
I have a List<CustomClass>
. I wish to create an integer using this List which holds the number of objects in the list which have a trueOrFalse
value of True
.
What is the best way to do this ? I assume there is a clever way to use Linq to accomplish this, rather than having to iterate over every object ?
Thanks a lot.
You can use Enumerable.Count
:
int numTrue = list.Count(cc => cc.trueOrFalse);
Remember to add using system.Linq;
Note that you should not use this method to check whether or not a sequence contains elements at all(list.Count(cc => cc.trueOrFalse) != 0
). Therefore you should use Enumerable.Any
:
bool hasTrue = list.Any(cc => cc.trueOrFalse);
The difference is that Count
enumerates the whole sequence whereas Any
will return true early as soon as it finds one element that passes the test predicate.
You can do that indeed simple with LINQ.
int amountTrue = list.Where(c => c.trueOrFalse).Count();
Or shorter with the Where in the count:
int amountTrue = list.Count(c => c.trueOrFalse);
Like Tim Schmelter stated: Add using System.Linq;
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