2011-11-26 28 views
19

我有List<int>并需要计算它有多少个元素(值为< 5) - 我该如何做?使用列表中的int <5计算元素<T>

+0

Yeesh!有人花了一大堆时间在下面回答4个答案。 –

+0

@ p.campbell - 是的,无论哪个人对外来的“Where”都是冒犯性的。 – Oded

+4

[使用Linq获取列表<>的项目数]的可能重复(http://stackoverflow.com/questions/3853010/get-item-count-of-a-list-using-linq) –

回答

55

Count()具有过载接受Predicate<T>

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

参见MSDN

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

事情是这样的:

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

试试这个:

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

最短的选项:

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

这也将做:

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

+1我其实真的很喜欢后面的方法,因为它们在性能方面非常相似,我认为这里的情况会更清楚一些。 – ForbesLindesay

35

不像其他的答案,这使用此重载做它在一个方法调用中的countextension method

using System.Linq; 

... 

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

注意,因为LINQ扩展方法在System.Linq命名空间中定义,你可能需要添加一个using语句如果它不在那里(应该是),请参考System.Core


参见:Extension methods defined by the Enumerable class.

+1

+1只有一个没有无关where子句。 –

+2

+1,因为你比abatischchev接受的答案早一分钟;) – Abel

+0

@Daniel:只有一个,是的:)) – abatishchev

5

TRY -

var test = new List<int>(); 
test.Add(1); 
test.Add(6); 
var result = test.Count(i => i < 5); 
7
int count = list.Count(i => i < 5); 
3
list.Where(x => x < 5).Count() 
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 
    } 
} 
+0

+1作为唯一不使用LINQ的答案。虽然我会更喜欢使用“foreach”而不是“for”。更好的方法是将谓词作为参数的泛化方法,然后使用lambda表示法进行调用。 – RenniePet