个性化阅读
专注于IT技术分析

LINQ sum()函数

在LINQ中, sum()函数用于计算集合/列表中各项的总和。

以下是在C#中定义LINQ sum函数的语法, 以汇总列表中的项目。

C#中LINQ Sum函数的语法

int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int Sum = Num.Sum();

根据以上语法, 我们使用LINQ Sum函数汇总” Num”列表中的项目。

现在, 我们将看到使用LINQ Sum()函数对C#应用程序中的集合/列表中的项目进行汇总的完整示例。

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)
        {   
//create array num with the initializing value
            int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            Console.WriteLine("Calculating the sum of all the elements of the array :");
//Num.Sum() is used to add the value of the Num array
            int Sum = Num.Sum();
            Console.WriteLine("The Sum is {0}", Sum);
            Console.ReadLine();
        }
    }
}

在上面的示例中, 我们使用sum函数计算数组列表” Num”中元素的总和。

执行上面的示例时, 我们得到的结果如下所示:

LINQ sum()函数

我们可以使用LINQ中的sum()函数对集合/列表中的项目进行汇总, 这是基于我们的要求的。


赞(1)
未经允许不得转载:srcmini » LINQ sum()函数

评论 抢沙发

评论前必须登录!