LINQ中的Aggregate用法总结

Aggregate这个语法可以做一些复杂的聚合运算,例如累计求和,累计求乘积。它接受2个参数,一般第一个参数是称为累积数(默认情况下等于第一个值),而第二个代表了下一个值。第一次计算之后,计算的结果会替换掉第一个参数,继续参与下一次计算。

一、Aggregate用于集合的简单的累加、阶乘

1.using System;
2.using System.Linq;
3.
4.class Program
5.{
6.static void Main()
7.{
8.int[] array = { 1, 2, 3, 4, 5 };
9.int result = array.Aggregate((a, b) => b + a);
10.// 1 + 2 = 3
11.// 3 + 3 = 6
12.// 6 + 4 = 10
13.// 10 + 5 = 15
14.Console.WriteLine(result);
15.
16. result = array.Aggregate((a, b) => b * a);
17.// 1 * 2 = 2
18.// 2 * 3 = 6
19.// 6 * 4 = 24
20.// 24 * 5 = 120
21.Console.WriteLine(result);
22.}
23.}

输出结果:

15
120
Aggregate它接受2个参数,一般第一个参数是称为累积数(默认情况下等于第一个值),而第二个代表了下一个值。

二、Aggregate,在字符串中反转单词的排序  

1.string sentence = "the quick brown fox jumps over the lazy dog";
2.string[] words = sentence.Split(' ');
3.string reversed = words.Aggregate((workingSentence, next) =>
4. next + " " + workingSentence);
5.Console.WriteLine(reversed);

 

输出结果:
dog lazy the over jumps fox brown quick the 

三、使用 Aggregate 应用累加器函数和结果选择器

下例使用linq的Aggregate方法找出数组中大于"banana", 长度最长的字符串,并把它转换大写。
1.string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };
2.string longestName =
3. fruits.Aggregate("banana",
4.(longest, next) =>
5. next.Length > longest.Length ? next : longest,
6. fruit => fruit.ToUpper());
7.Console.WriteLine(
8."The fruit with the longest name is {0}.",
9. longestName);

 

输出结果:
The fruit with the longest name is PASSIONFRUIT. 

四、使用 Aggregate 应用累加器函数和使用种子值

下例使用linq的Aggregate方法统计一个数组中偶数的个数。
1.int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };
2.
3.//统计一个数组中偶数的个数,种子值设置为0,找到偶数就加1
4.int numEven = ints.Aggregate(0, (total, next) =>
5. next % 2 == 0 ? total + 1 : total);
6.
7.Console.WriteLine("The number of even integers is: {0}", numEven);

 

输出结果:

The number of even integers is: 6

除此之外LINQ中的Aggregate还可以用于递归调用。 
posted @ 2015-11-26 13:45  狂风逆袭  阅读(1809)  评论(0编辑  收藏  举报