Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic List, items counting with conditional-statement

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);

like image 834
Zeeshanef Avatar asked Sep 04 '13 14:09

Zeeshanef


People also ask

How to count total number of elements in a List in C#?

Count Property is used to get the total number of elements contained in the List.

What is generic list in C#?

Generic List<T> is a generic collection in C#. The size can be dynamically increased using List, unlike Arrays.

How do you create a list in C sharp?

The following example shows how to create list and add elements. In the above example, List<int> primeNumbers = new List<int>(); creates a list of int type. In the same way, cities and bigCities are string type list. You can then add elements in a list using the Add() method or the collection-initializer syntax.

What is count in C#?

To count the number of elements in the C# array, we can use the count() method from the IEnumerable. It is included in the System. Linq. Enumerable class. The count method can be used with any type of collection such as an array, ArrayList, List, Dictionary, etc.


1 Answers

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.

like image 199
Jon Skeet Avatar answered Nov 15 '22 15:11

Jon Skeet