Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count elements with int < 5 in List<T>

Tags:

I have a List<int> and need to count how many elements with (value < 5) it has - how do I do this?

like image 659
abolotnov Avatar asked Nov 26 '11 16:11

abolotnov


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.

Which is the method is used to count the number of items in the list?

To count the number of elements of a string, the len() method can be used.

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.

How check if list is empty C#?

Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.


2 Answers

Count() has an overload accepting Predicate<T>:

int count = list.Count(x => x < 5); 

See MSDN

like image 52
abatishchev Avatar answered Oct 19 '22 13:10

abatishchev


Unlike other answers, this does it in one method call using this overload of the count extension method:

using System.Linq;  ...  var count = list.Count(x => x < 5); 

Note that since linq extension methods are defined in the System.Linq namespace you might need to add a using statement, and reference to System.Core if it's not already there (it should be).


See also: Extension methods defined by the Enumerable class.

like image 34
George Duckett Avatar answered Oct 19 '22 15:10

George Duckett