LINQ Sum Function to Sum up Collection Items

  Total Views : 335
  Comments : 0
 
  Keywords : How to use sum function to sum items of collection with example, LINQ sum function to get sum of items from list with example, LINQ aggregate sum function to sum up list of item with example

Here we will learn linq aggregate function / operator sum() in c#, vb.net with example and how to use linq sum() function / operator to sum up items in list / collection in c#, vb.net with example.

LINQ Aggregate Sum() Function

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

Syntax of LINQ Sum() Function

Following is the syntax of using LINQ sum function to sum up items in list.

 

C# Code

 

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

int Sum = Num.Sum();

VB.NET Code

 

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

Dim Sum As Integer = Num.Sum()

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

LINQ Sum() Function Example 

Now we will see the example of using linq Sum() function to sum up items in collection / list.

 

C# Code

 

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();

}

}

}

VB.NET Code

 

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() to calculate the sum of the elements from the array list “Num”. Now we will run and see the output that would be like as shown below

Output of LINQ Sum() Function

Following is the result of using LINQ Sum() function to sum up items in array list.

 

Calculating the Sum of all the elements of the array :

 

The Sum is 45

This is how we can use Sum() function in linq to sum up items in list / collection

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User