I have a List<int>
and need to count how many elements with (value < 5) it has - how do I do this?
Asked
Active
Viewed 2.3k times
25

abatishchev
- 98,240
- 88
- 296
- 433

abolotnov
- 4,282
- 9
- 56
- 88
-
Yeesh! Someone spent a bunch of time downvoting 4 answers below. – p.campbell Nov 26 '11 at 17:09
-
@p.campbell - Yeah, whomever it was took offence to the extraneous `Where`. – Oded Nov 26 '11 at 18:28
-
4possible duplicate of [Get item count of a list<> using Linq](http://stackoverflow.com/questions/3853010/get-item-count-of-a-list-using-linq) – Raymond Chen Nov 30 '11 at 14:38
10 Answers
37
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.

George Duckett
- 31,770
- 9
- 95
- 162
-
2+1 because you were one minute earlier than the accepted answer of abatischchev ;) – Abel Nov 29 '11 at 17:25
18
The shortest option:
myList.Count(v => v < 5);
This would also do:
myList.Where(v => v < 5).Count();

Oded
- 489,969
- 99
- 883
- 1,009
-
+1 I actually really like the later method here as they are pretty much equivalent performance wise and I think it's a little clearer what's going on here. – ForbesLindesay Nov 30 '11 at 04:20
6
List<int> list = ...
int count = list.Where(x => x < 5).Count();

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
6
Try -
var test = new List<int>();
test.Add(1);
test.Add(6);
var result = test.Count(i => i < 5);

ipr101
- 24,096
- 8
- 59
- 61
2
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
}
}

abatishchev
- 98,240
- 88
- 296
- 433

kpratama
- 133
- 2
- 7
-
+1 For being the only answer that doesn't use LINQ. Although I would have preferred use of "foreach" instead of "for". Even better would be a generalized method that has a predicate as the parameter and can then be invoked using lambda notation. – RenniePet Mar 24 '14 at 10:47