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: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 useEnumerable.Any:The difference is that
Countenumerates the whole sequence whereasAnywill return true early as soon as it finds one element that passes the test predicate.