首頁  >  文章  >  後端開發  >  顯示 LINQ Aggregate() 方法用法的 C# 程序

顯示 LINQ Aggregate() 方法用法的 C# 程序

WBOY
WBOY轉載
2023-09-15 23:25:06809瀏覽

显示 LINQ Aggregate() 方法用法的 C# 程序

Aggregate() 方法是一種強大的 LINQ 方法,可讓您對元素序列執行歸約操作。此方法可用於對一組資料執行計算,例如求一組數字的總和、乘積或最大值。在本文中,我們將探討如何在 C# 程式中使用 Aggregate() 方法。

什麼是Aggregate()方法?

Aggregate() 方法是一種 LINQ 擴充方法,它採用兩個參數:種子值和對元素序列執行歸約運算的函數。種子值是運算的初始值,函數指定如何將序列中的每個元素與先前的結果組合。

Aggregate()方法的語法

public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)

範例:使用 Aggregate() 方法求數字序列的總和

讓我們來看一個使用Aggregate()方法來找出一系列數字的和的範例。

using System.IO;
using System;
using System.Linq;

class Program {
   static void Main(string[] args) {
      int[] numbers = { 1, 2, 3, 4, 5 };
   
      int sum = numbers.Aggregate((x, y) => x + y);
   
      Console.WriteLine("The sum of the sequence is: {0}", sum);
   }
}

在這段程式碼中,我們有一個名為numbers的整數陣列。我們使用Aggregate()方法透過傳遞一個lambda表達式將兩個元素相加來計算序列的總和。

輸出

The sum of the sequence is: 15

範例:使用 Aggregate() 方法求數字數列的乘積

現在,讓我們來看一個範例,了解如何使用 Aggregate() 方法找出數字序列的乘積。

using System;
using System.Linq;

class Program {
   static void Main() {
      int[] numbers = { 1, 2, 3, 4, 5 };
      int product = numbers.Aggregate(1, (x, y) => x * y);
      Console.WriteLine("The product of the sequence is: {0}", product);
   }
}

在這段程式碼中,我們有一個名為numbers的整數陣列。我們使用Aggregate()方法透過傳遞初始值1和一個lambda表達式將兩個元素相乘來計算序列的乘積。

輸出

The product of the sequence is: 120

結論

Aggregate() 方法是一個強大的 LINQ 方法,可以用來對元素序列執行約簡操作。在本文中,我們探討如何在 C# 程式中使用 Aggregate() 方法來找出一系列數字的和和積。

以上是顯示 LINQ Aggregate() 方法用法的 C# 程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除
上一篇:C# 中的數字下一篇:C# 中的數字