如何使用Aggregate方法统计列表中大于指定值的整数个数
用Aggregate统计符合条件的元素数量实现方法
核心逻辑
Aggregate方法的本质是迭代遍历集合时维护一个累加状态,我们只需要将累加状态设置为符合条件的元素计数即可实现需求:
- 给累加器设置初始值
0(未遍历任何元素时符合条件的数量为0) - 每遍历一个元素就判断是否满足「大于指定阈值」的条件,符合就给累加器加1,否则保持原值不变
代码示例
using System.Collections.Generic; using System.Linq; // 示例数据 List<int> list = new List<int>() { 100, 200, 300, 400, 500 }; int targetThreshold = 250; // 用Aggregate统计 int resultCount = list.Aggregate( seed: 0, // 初始计数为0 func: (currentCount, item) => item > targetThreshold ? currentCount + 1 : currentCount ); Console.WriteLine(resultCount); // 输出3,符合预期
注意事项
不要使用不带初始种子的
Aggregate重载,该重载会将集合的第一个元素作为累加器初始值,会导致计数逻辑完全错误,必须显式传入初始值0作为计数起点。
内容的提问来源于stack exchange,提问作者Hleb Butkevich
相关产品推荐
相关产品推荐

