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.
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)
List<int> list = ...
int count = list.Where(x => x < 5).Count();
Run Code Online (Sandbox Code Playgroud)
试试 -
var test = new List<int>();
test.Add(1);
test.Add(6);
var result = test.Count(i => i < 5);
Run Code Online (Sandbox Code Playgroud)