Find the sum of a list, where is the property == true?

In my C # code, I have a list of CustomClass types. This class contains the boolean property trueOrFalse .

I have a List<CustomClass> . I want to create an integer using this list, which contains the number of objects in the list that are trueOrFalse True .

What is the best way to do this? I assume there is a smart way to use Linq to accomplish this, instead of iterating over each object?

Thank you very much.

+4
source share
5 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 a sequence of elements contains or not ( list.Count(cc => cc.trueOrFalse) != 0 ). Therefore you should use Enumerable.Any :

 bool hasTrue = list.Any(cc => cc.trueOrFalse); 

The difference is that Count lists the entire sequence, whereas Any will return true sooner as soon as it finds one element that passes the test predicate.

+13
source

You can do this very simply with LINQ.

 int amountTrue = list.Where(c => c.trueOrFalse).Count(); 

Or shorter with "Where in the bill":

 int amountTrue = list.Count(c => c.trueOrFalse); 

As Tim Schmelter stated: Add using System.Linq;

+4
source
  list.Count(a => a.TrueOrFalse); 

And I took the liberty of giving your property a capital letter at the beginning.

+2
source

This is trivial with LINQ:

 list.Count(x => x.trueOrFalse); 

Just name the Count extension method in your list and go to state. In your case, this is just your logical property.

+1
source
 var count = listOfCustomClass.Where(a => a.trueOrFalse).Count(); 
0
source

Source: https://habr.com/ru/post/1441561/


All Articles