卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章20384本站已运行347

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

<?xml encoding="utf-8" ?>

显示 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() 方法来找到一系列数字的和和积。

卓越飞翔博客
上一篇: 如何使用C# FileStream类?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏