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);
Count Property is used to get the total number of elements contained in the List.
Generic List<T> is a generic collection in C#. The size can be dynamically increased using List, unlike Arrays.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With