Linq: Aggregate

Aggregate累加器

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 ,如此依次的遍历执行下去,直至结束。

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

1
2
3
4
5
6
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了。

 

  时间2014-12-03,在浏览CSDN,在上面看到一题,正好用到Aggregate,就把博客完善一下,增加一个例子。题目就不自己写了,直接给出截图了,呵呵。

下面直接给代码了。

            string seed = Console.ReadLine();
            Console.WriteLine("请输入n:");
            int copy = Convert.ToInt32(Console.ReadLine());
            long result = 0;
            for (int i = 1; i <= copy; i++)
            {
                string temp = Enumerable.Repeat(seed, i).Aggregate("", (current, item) => current + item);
                result += Convert.ToInt32(temp);
            }
            Console.WriteLine(result);
            Console.ReadKey();


输出结果就不再给了。其中对Repeat不熟悉的可以参看CSDN上的例子http://msdn.microsoft.com/en-us/library/bb348899.aspx,或者本人的例子:打印星号(*)三角形(C# Linq实现)的小例子

  在.NET reflector中的实现是一下函数。

   好了,今天的就写到这,以后发现新的有代表性的例子时,再添加。

 

 

文章原址:http://www.cnblogs.com/superCow/p/3804134.html   作者:Super Cow

posted @ 2014-11-18 13:20  荣码一生  阅读(367)  评论(0编辑  收藏  举报