Aggregate()函数

Aggregate()函数 首页 / LinQ入门教程 / Aggregate()函数

在LINQ中,Aggregate()函数用于对列表的每一项进行操作。Aggregate()函数对第一个和第二个元素执行操作,然后继续执行结果。对于下一次操作,它将考虑上一个结果和第三个元素,然后继续,依此类推。

C#中LINQ聚合函数的语法

int[] Num = { 1, 2, 3, 4 };
double Average = Num.Aggregate((a, b) => a + b);
 Console.WriteLine("{0}", Average); //Output 10 ((1+2)+3)+4

在上面的语法中,我们用两个元素1和2进行加法,并使3,然后将前一个结果3和下一个元素3进行加法,使6与下一个元素4相加,结果将是10。

现在,我们将展示使用C#中的Linq Aggregate()函数计算整数数组中所有数字的乘积的示例。

C#中LINQ聚合函数的语法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
    {
static void Main(string[] args)
        {
//here we are creating the array Num type of int
int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Console.WriteLine("Product of the element:");
 //Now we will calculate the average of the numbers by applying the Aggregate function
double Average = Num.Aggregate((a, b) => a * b);

Console.WriteLine("Product is {0}", Average); //Output 362880 ((((((((1*2)*3)*4)*5)*6)*7)*8)*9)
//reate an array of string of the name charlist
string[] charlist = { "a", "b", "c", "d" };

var concat = charlist.Aggregate((a, b) => a + ',' + b);

Console.WriteLine("the Concatenated String: {0}", concat); // Output a,b,c,d

Console.ReadLine();
        }
    }
}

In the above examples, there is an integer array Num. We calculated the product of all the elements present in the given array. For this, we have to specify a Lambda Expression. In the Lambda Expression, we took two input parameters, "a" and "b." And on the right-hand side, we multiply the parameters of input. Now we would be getting the product of all the numbers.

这些步骤将描述上述示例的功能。

  1. The first element 1 from the array is assigned to a. The second element 2 is assigned to b.
  2. The product of the two elements is calculated using Lambda Expression. The outcome of the first two-element (1 and 2) is stored in 'a'. Now the value of b is null.
  3. The first two elements have been used lambda will take the third element and assigned its value to b, which was null.
  4. Now "a" contains the product of the first two elements (1 and 2), and b contains the third (3) element. Now a and b multiplied according to lambda, and the resultant value is stored in a. Now b is set to null.
  5. The fourth element from the array is assigned to b and contains the product of the first three elements. This process will continue till the last element, and the product is finally displayed on the console.

以同样的方式,我们在LINQ中将项目(a、b、c、d)的列表连接在单独的字符串中。

当我们执行上面的LINQ Aggregate()函数时,我们将得到如下所示的结果:

无涯教程网

输出

LINQ Aggregate() Function




祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

iOS开发高手课 -〔戴铭〕

全栈工程师修炼指南 -〔熊燚(四火)〕

架构实战案例解析 -〔王庆友〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

eBPF核心技术与实战 -〔倪朋飞〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

Web 3.0入局攻略 -〔郭大治〕

结构会议力 -〔李忠秋〕

Rust 语言从入门到实战 -〔唐刚〕

好记忆不如烂笔头。留下您的足迹吧 :)