General list, counting elements with conditional expression

I have a general list. it has a ListfilesToProcess.Count property that returns the total number of elements, but I want to count a certain number of elements in a list with a conditional expression.

I do it like this:

int c = 0; foreach (FilesToProcessDataModels item in ListfilesToProcess) { if (item.IsChecked == true) c++; } 

Is there a shorter way, for example, int c = ListfilesToProcess.count (item => item.IsChecked == true);

+4
source share
1 answer

Yes, use the LINQ Count method with predicate overload:

 int count = ListFilesToProcess.Count(item => item.IsChecked); 

In general, whenever you feel that you want to get rid of the loop (or simplify it), you should look at LINQ.

+14
source

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


All Articles