Aggregate累加器

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

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

这个方法的功能实际上是对,可枚举的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 ,如此依次的遍历执行下去,直至结束。blog

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

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了。it

相关文章
相关标签/搜索