计算List <T>中int <5的元素

abo*_*nov 21 .net c# linq list count

我有一个List<int>并且需要计算它有多少元素(值<5) - 我该怎么做?

aba*_*hev 58

Count()有超载接受Predicate<T>:

int count = list.Count(x => x < 5);
Run Code Online (Sandbox Code Playgroud)

请参阅MSDN


Geo*_*ett 36

与其他答案不同,这是使用count 扩展方法的这个重载在一个方法调用中完成的:

using System.Linq;

...

var count = list.Count(x => x < 5);
Run Code Online (Sandbox Code Playgroud)

请注意,由于linq扩展方法是在System.Linq命名空间中定义的,因此您可能需要添加一个using语句,并引用System.Core它是否已经存在(它应该是).


另请参见:定义的扩展方法Enumerable.

  • +1因为你比abatischchev的接受答案提前一分钟;) (2认同)

Ode*_*ded 16

最短的选择:

myList.Count(v => v < 5);
Run Code Online (Sandbox Code Playgroud)

这也可以:

myList.Where(v => v < 5).Count();
Run Code Online (Sandbox Code Playgroud)


Mat*_*ott 7

int count = list.Count(i => i < 5);
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 5

List<int> list = ...
int count = list.Where(x => x < 5).Count();
Run Code Online (Sandbox Code Playgroud)


ipr*_*101 5

试试 -

var test = new List<int>();
test.Add(1);
test.Add(6);
var result =  test.Count(i => i < 5);
Run Code Online (Sandbox Code Playgroud)