using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace LambdaSample{ class Program { static void Mai...
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LambdaSample { class Program { static void Main(string[] args) { int[] myIntArray = { 1,2, 3, 4, 5 }; //累加器計算數組總和 int result = myIntArray.Aggregate((paramA, paramB) => paramA + paramB); int result1 = myIntArray.Aggregate<int>((paramA, paramB) => paramA + paramB); int result2 = myIntArray.Aggregate<int, int>(0, (paramA, paramB) => paramA + paramB); //遞歸計算數組總和 int result3 = count(5); Console.WriteLine("The Result is: " + result); Console.WriteLine("The Result1 is: " + result1); Console.WriteLine("The Result2 is: " + result2); Console.WriteLine("The Result3 is: " + result3); string[] myStrArray = { "Admin", "Change", "ByPage" }; //字元串數組拼接 string strResult = myStrArray.Aggregate((paramA, paramB) => paramA + " " + paramB); //字元串數組字元串總長度計算 int result4 = myStrArray.Aggregate<string, int>(0, (a, b) => a + b.Length); //字元串數組拼接2,增加字元串"Some curries: " string strResult1 = myStrArray.Aggregate<string, string>("Some curries: ", (a, b) => a + " " + b); //字元串數組字元串總長度計算2 int result5 = myStrArray.Aggregate<string, string, int>("Some curries: ", (a, b) => a + " " + b, a => a.Length); Console.WriteLine("The StrResult is: " + strResult); Console.WriteLine("The Result4 is: " + result4); Console.WriteLine(strResult1); Console.WriteLine("The Result5 is: " + result5); Console.ReadKey(); } static int count(int n) { if (n == 1) { return 1; } return n + count(n - 1); } } }
該例子源代碼摘自C#入門經典第5版第14章(387頁)