I have a List<int>
and need to count how many elements with (value < 5) it has - how do I do this?
Count Property is used to get the total number of elements contained in the List.
To count the number of elements of a string, the len() method can be used.
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.
Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.
Count()
has an overload accepting Predicate<T>
:
int count = list.Count(x => x < 5);
See MSDN
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.
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