LINQ Sum Function to Sum up Collection Items

In LINQ, Sum function is useful to calculate the sum of items in a collectionlist.

 

Following is the syntax of defining the LINQ sum function in c# and vb.net to sum up the items in list.

Syntax of LINQ Sum() Function C# 

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

int Sum = Num.Sum();

LINQ Sum() Function Syntax VB.NET

Dim Num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Dim Sum As Integer = Num.Sum()

If you observe the above syntaxes, we are summing up the items in "Num" list using linq Sum() function.

 

Now, we will see the examples of using linq Sum() function in c# and vb.net to sum up the items in collection / list.

LINQ Sum() Function Example C#

using System;

using System.Collections.Generic;

using System.Linq;

namespace Linqtutorials

{

class Program

{

static void Main(string[] args)

{

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

Console.WriteLine("Calculating the sum of all the elements of the array :");

int Sum = Num.Sum();

Console.WriteLine("The Sum is {0}", Sum);

Console.ReadLine();

}

}

}

LINQ Sum() Function Example VB.NET

Module Module1

Sub Main()

Dim Num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Console.WriteLine("Calculating the sum of all the elements of the array :")

Dim Sum As Integer = Num.Sum()

Console.WriteLine("The Sum is {0}", Sum)

Console.ReadLine()

End Sub

End Module

Here, we used Sum() function to calculate the sum of the elements in the array list “Num”.

 

When we execute the above examples, we will get the result like as shown below.

 

Calculating the Sum of all the elements of the array :

 

The Sum is 45

This is how we can use the Sum() function in linq to sum up the items in collection / list based on our requirements. 

Topics Covered