LINQ Sum Function to Sum up Collection Items

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

 

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 in C#

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

LINQ Sum() Function Syntax in 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 the "Num" list using LINQ Sum() function.

 

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

LINQ Sum() Function Example in 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 in 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 the 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 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 the collection/list based on our requirements.