C#程序:演示LINQ Aggregate()方法的用法
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() 方法来查找数字序列的总和和乘积。
广告