IEnumerable接口的Aggregate方法
以前小猪为了累加一个集合中的类容通常会写出类似这样的C#代码:
string result ="":
foreach (var item in items)
{
result+=item.centent;
}
大概意思就是遍历集合中的每一项来累加其中的一个值。今天小猪才发现其实.NET的集合已经提供了该功能:那就是小猪现在讲的IEnumerable<T>接口的Aggregate方法:
该方法提供了两个重载版本
版本1:Aggregate<TSource>(Func<TSource, TSource, TSource>):已重载。 对序列应用累加器函数。 (由 Enumerable 定义。)
版本2:Aggregate<TSource, TAccumulate>(TAccumulate, Func<TAccumulate, TSource, TAccumulate>)已重载。 对序列应用累加器函数。 将指定的种子值用作累加器初始值。 (由Enumerable 定义。)
public static TAccumulate Aggregate<TSource, TAccumulate>(
this IEnumerable<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func
)
由定义可以看出该方法是个拓展方法,所以在使用时不需要传递第一个参数。
此方法的工作原理是对 source 中的每个元素调用一次 func。 每次调用 func 时,Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>) 都将传递序列中的元素和聚合值(作为 func 的第一个参数)。 将 seed 参数的值用作聚合的初始值。 用 func 的结果替换以前的聚合值。Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>) 返回 func 的最终结果。
若要简化一般的聚合运算,标准查询运算符还可以包含一个通用的计数方法(即 Count)和四个数值聚合方法(即 Min、Max、Sum 和 Average)。
下面的代码示例演示如何使用 Aggregate 应用累加器函数和使用种子值。
int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 }; // Count the even numbers in the array, using a seed value of 0.
int numEven = ints.Aggregate(0, (total, next) =>next % 2 == 0 ? total + 1 : total); Console.WriteLine("The number of even integers is: {0}", numEven); // This code produces the following output:
//
// The number of even integers is: 6
最新文章
- 架构师养成记--15.Disruptor并发框架
- XMPP iOS客户端实现一:服务器
- Invalid escape sequence(valid ones are \b \t \n \f \r \"; \&#39; \\)
- Xamarin开发Android笔记:TextView行间距设定
- Windows环境下32位汇编语言程序设计(典藏版)
- windows 2008 R2 64位系统,找到Microsoft Excel 应用程序
- CAF(C++ actor framework)使用随笔(unbecome与keep_behavior用法)
- centos 卸载自带的 java
- maya 操作自我整理(二)
- Mysql 创建联合主键
- Linux的起源、特点和版本号
- HDU 1114 Piggy-Bank(判断是否恰好装满的背包)
- SQL Server 手把手教你使用profile进行性能监控
- ubuntu下创建python的虚拟环境
- 解决Spring Boot 使用RedisTemplate 存储键值出现乱码 \xac\xed\x00\x05t\x00
- 记一次物理机安装centos7.5 出现黑屏的问题
- 如何在ubuntu中安装php
- 无备份mysql删除表后恢复
- React Native 教程:001 - 如何运行官方控件示例 App
- MSSQL &#183; 最佳实践 &#183; 利用文件组实现冷热数据隔离备份方案
热门文章
- 【002: NetBeans 的 代码补全】
- [Phalcon] Phalcon系统默认事件列表
- RobotFrameWork WebService Soap接口测试 (一)
- JavaWeb应用开发架构浅谈
- php中rsa加密解密验证
- [充电]多线程无锁编程--原子计数操作:__sync_fetch_and_add等12个操作
- [CCF] Z字形扫描
- C++提前delete
- 红字差评系列3.abcd
- 手把手教iOS生成.a包及常见的问题