Find sum of List where property == true?

.net, c#, linq, list

Solution

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.

Problem

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.

Original source