abolotnov
abolotnov

Reputation: 4332

Count elements with int < 5 in List<T>

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

Answers (10)

kpratama
kpratama

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

George Duckett
George Duckett

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

akoso
akoso

Reputation: 620

list.Where(x => x < 5).Count()

Upvotes: 4

Matthew Abbott
Matthew Abbott

Reputation: 61599

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

Upvotes: 8

ipr101
ipr101

Reputation: 24236

Try -

var test = new List<int>();
test.Add(1);
test.Add(6);
var result =  test.Count(i => i < 5);

Upvotes: 6

abatishchev
abatishchev

Reputation: 100308

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

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

See MSDN

Upvotes: 62

Oded
Oded

Reputation: 499172

The shortest option:

myList.Count(v => v < 5);

This would also do:

myList.Where(v => v < 5).Count();

Upvotes: 18

p.campbell
p.campbell

Reputation: 100607

Try this:

int c = myList.Where(x=>x<5).Count();

Upvotes: 3

JohnD
JohnD

Reputation: 14767

Something like this:

var count = myList.Where(x => x < 5).Count();

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039228

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

Upvotes: 6

Related Questions