【LINQ】 Aggregate的用法
原文地址:http://www.studyofnet.com/news/1154.html
1.Aggregate用于集合的简单的累加、阶乘
using System; using System.Linq; class Program { static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int result = array.Aggregate((a, b) => b + a); // 1 + 2 = 3 // 3 + 3 = 6 // 6 + 4 = 10 // 10 + 5 = 15 Console.WriteLine(result); result = array.Aggregate((a, b) => b * a); // 1 * 2 = 2 // 2 * 3 = 6 // 6 * 4 = 24 // 24 * 5 = 120 Console.WriteLine(result); } } //输出结果: //15 //120
2.Aggregate,在字符串中反转单词的排序
string sentence = "the quick brown fox jumps over the lazy dog"; string[] words = sentence.Split(' '); string reversed = words.Aggregate((workingSentence, next) =>next + " " + workingSentence); Console.WriteLine(reversed); //输出结果: //dog lazy the over jumps fox brown quick the
3.使用 Aggregate 应用累加器函数和结果选择器
//下例使用linq的Aggregate方法找出数组中大于"banana", 长度最长的字符串,并把它转换大写。 string[] fruits ={ "apple", "mango", "orange", "passionfruit", "grape" }; string longestName = fruits.Aggregate("banana", (longest, next) => next.Length > longest.Length ? next : longest, fruit => fruit.ToUpper()); Console.WriteLine( "The fruit with the longest name is {0}.",longestName); //输出结果: //The fruit with the longest name is PASSIONFRUIT.
4.使用 Aggregate 应用累加器函数和使用种子值
//下例使用linq的Aggregate方法统计一个数组中偶数的个数。 int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 }; //统计一个数组中偶数的个数,种子值设置为0,找到偶数就加1 int numEven = ints.Aggregate(0, (total, next) => next % 2 == 0 ? total + 1 : total); Console.WriteLine("The number of even integers is: {0}", numEven); //输出结果: //The number of even integers is: 6
浙公网安备 33010602011771号