在LINQ中,Aggregate()函数用于对列表的每一项进行操作。Aggregate()函数对第一个和第二个元素执行操作,然后继续执行结果。对于下一次操作,它将考虑上一个结果和第三个元素,然后继续,依此类推。
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()函数计算整数数组中所有数字的乘积的示例。
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.
这些步骤将描述上述示例的功能。
以同样的方式,我们在LINQ中将项目(a、b、c、d)的列表连接在单独的字符串中。
当我们执行上面的LINQ Aggregate()函数时,我们将得到如下所示的结果:
输出
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
HarmonyOS快速入门与实战 -〔QCon+案例研习社〕