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

2023年 9月 16日 13.9k 0

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

Aggregate() 方法是一种功能强大的 LINQ 方法,允许您对元素序列执行归约操作。此方法可用于对一组数据执行计算,例如求一组数字的总和、乘积或最大值。在本文中,我们将探讨如何在 C# 程序中使用 Aggregate() 方法。

什么是Aggregate()方法?

Aggregate() 方法是一种 LINQ 扩展方法,它采用两个参数:种子值和对元素序列执行归约操作的函数。种子值是运算的初始值,函数指定如何将序列中的每个元素与之前的结果组合起来。

Aggregate()方法的语法

public static TAccumulate Aggregate(this IEnumerable source, TAccumulate seed, Func 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# 程序的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论