欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Aggregate累加器

发布时间:2025/5/22 编程问答 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Aggregate累加器 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

今天看东西的时候看见这么个扩展方法Aggregate(累加器)很是陌生,于是乎查了查,随手记录一下。
直接看一个最简答的版本,其他版本基本没什么区别,需要的时候可看一下

public static TSource Aggregate<TSource>(
this IEnumerable<TSource> source,
Func<TSource, TSource, TSource> func
)

这个方法的功能其实是对,可枚举的IEnumerable<TSource>某种数据,从前两个遍历对象开始逐个,作为输入进行自定
义的操作,这个方法还是蛮有用的,看几个例子。

private void button7_Click(object sender, EventArgs e){string sentence = "the quick brown fox jumps over the lazy dog";string[] words = sentence.Split(' ');Func<string, string, string> temp = test;string reversed = words.Aggregate("",temp);//string reversed=words.Aggregate((workingSentence, next) =>next + " " + workingSentence);MessageBox.Show(reversed);}public string test(string para1, string para2){return para2 + " " + para1;}

  这里我没用msdn直接提供的lambda方式,目的就是为了方便调试查看下。先给出结果吧dog lazy the over jumps fox brown quick the

其执行过程是这样滴,第一次 para1 为the ,para2为 quick,返回了 quick the, 并且作为下次的 para1,para2 为brown ,如此依次的遍历执行下去,直至结束。

  再给一个例子可以看出许多应用。计算数据中的整数的个数

private void button8_Click(object sender, EventArgs e){int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };int numEven = ints.Aggregate(0, (total, next) =>next % 2 == 0 ? total + 1 : total);MessageBox.Show("The number of even integers is: " + numEven);}

  恩恩,这都是msdn直接给出的例子,那么很多类似的统计或者计算累的需求是不是就可以考虑下Aggregate了。

转载于:https://www.cnblogs.com/superCow/p/3804134.html

《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读

总结

以上是生活随笔为你收集整理的Aggregate累加器的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。