Reputation: 4332
I have a List<int>
and need to count how many elements with (value < 5) it has - how do I do this?
Upvotes: 25
Views: 24842
Reputation: 133
int c = 0;
for (i = 0; i > list.Count; i++)
{
// The "for" is check all elements that in list.
if (list[i] < 5)
{
c = c + 1; // If the element is smaller than 5
}
}
Upvotes: 2
Reputation: 32438
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.
Upvotes: 37
Reputation: 24236
Try -
var test = new List<int>();
test.Add(1);
test.Add(6);
var result = test.Count(i => i < 5);
Upvotes: 6
Reputation: 100308
Count()
has an overload accepting Predicate<T>
:
int count = list.Count(x => x < 5);
See MSDN
Upvotes: 62
Reputation: 499172
The shortest option:
myList.Count(v => v < 5);
This would also do:
myList.Where(v => v < 5).Count();
Upvotes: 18
Reputation: 1039228
List<int> list = ...
int count = list.Where(x => x < 5).Count();
Upvotes: 6