Aggregate 雖被歸類為複雜方法,實則功能強大,可簡化多種聚合運算。
int[] nums = {1,2,3,4,5,6,7,8,9,10};
int sum1 = nums.Sum();
int sum2 = nums.Aggregate((i,j) => i+j); // 相同結果,但更底層
string[] words = {"Able","was","I","ere","I","saw","Elba"};
string s = words.Aggregate((a,n) => a + " " + n);
// 結果:"Able was I ere I saw Elba" (拿破崙名言回文)
string reverse = words.Aggregate((a,n) => n.Reverse() + " " + a);
配合自訂 Reverse() 擴展可實現單字反轉與順序反轉雙重效果。
byte[] data = {0x31,0x32,0x33,0x34,0x35};
byte checkSum = data.Aggregate((a,n) => (byte)(a ^ n));
適用於串口通訊校驗碼計算。Aggregate 低階特性使其能實現 Sum/Max 等高階方法無法涵蓋的邏輯。