- int[] numbers = new int[] { 1, 2, 3, 4, 5 };
- int product = numbers.Aggregate((total, next) => total * next);
- Console.WriteLine(product);
numbers(資料來源)有5個項目,分別為1, 2, 3, 4, 5
Aggregate 方法會讓他們分別去呼叫 Func 泛型委派(內容由我們實作)
所以代表 Func 會執行5次:呼叫次數 total next 1 1 2 2 2 3 3 6 4 4 24 5 5 120
total:代表彙總值,若 Aggregate 方法沒有去初始化 total ,則就為資料來源中第一個項目。
每次計算完成後的結果會取代掉total
next: 將要用來計算的下一個項目
第5次計算時,發現 next 已無資料,代表計算完成。最後計算結果就是 total个人感觉类似 遍历操作!!
LinQ方法之---------Aggregate 含义分析
最新推荐文章于 2024-09-02 23:30:09 发布