25

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

abatishchev
  • 98,240
  • 88
  • 296
  • 433
abolotnov
  • 4,282
  • 9
  • 56
  • 88

10 Answers10

62

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

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

See MSDN

abatishchev
  • 98,240
  • 88
  • 296
  • 433
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
8
int count = list.Count(i => i < 5);
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
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
4

Something like this:

var count = myList.Where(x => x < 5).Count();
JohnD
  • 14,327
  • 4
  • 40
  • 53
4
list.Where(x => x < 5).Count()
akoso
  • 620
  • 4
  • 10
3

Try this:

int c = myList.Where(x=>x<5).Count();
p.campbell
  • 98,673
  • 67
  • 256
  • 322
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