Generic List, items counting with conditional-stat

2019-05-01 17:54发布

问题:

I have a Generic List. it has a ListfilesToProcess.Count property which returns total number of items, but I want to count certain number of items in list with conditional-statement.

I am doing it like this:

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

Is there any shorter way like int c = ListfilesToProcess.count(item => item.IsChecked == true);

回答1:

Yes, use LINQ's Count method, with the overload taking a predicate:

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

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