C# 中的 Aggregate 方法


在 C# 中使用 Aggregate 方法進行數學運算,例如求和、求最小值、求最大值、求平均值等。

我們來看一個使用 Aggregate 方法計算陣列元素乘積的示例。

這是我們的陣列 -

int[] arr = { 10, 15, 20 };

現在,使用 Aggregate() 方法 -

arr.Aggregate((x, y) => x * y);

以下是完整程式碼 -

範例

 線上範例

using System;
using System.Linq;
using System.IO;
public class Demo {
   public static void Main() {
      int[] arr = { 10, 15, 20 };
      // Multiplication
      int res = arr.Aggregate((x, y) => x * y);
      Console.WriteLine(res);
   }
}

產出

3000

更新於: 2020 年 6 月 22 日

888 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始使用
廣告