Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find sum of List where property == true?

Tags:

c#

.net

list

linq

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.

like image 603
Simon Kiely Avatar asked Dec 01 '22 05:12

Simon Kiely


2 Answers

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.

like image 77
Tim Schmelter Avatar answered Dec 05 '22 17:12

Tim Schmelter


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;

like image 41
SynerCoder Avatar answered Dec 05 '22 16:12

SynerCoder