C# - Example of LINQ Aggregate() Method | Sum of Array Elements

Learn, how to calculate the sum of array elements using the Linq Aggregate() method in C#? By Nidhi Last updated : April 01, 2023

Here, we will create an array of integer elements and then calculate the sum all array elements using Linq  Aggregate() method.

C# program to calculate the sum of array elements using the LINQ Aggregate() method

The source code to calculate the sum of array elements using the Aggregate() method, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to calculate the sum of array elements 
//using the Linq Aggregate() method.

using System;
using System.Linq;

class LinqDemo
{
    static void Main(string[] args)
    {
        int[] values = { 10, 8, 2, 2, 7, 4};
        int sum = 0;
        
        sum = values.Aggregate((val1, val2) => val1 + val2);
        
        Console.WriteLine("Sum is : "+sum);
    }
}

Output

Sum is : 33
Press any key to continue . . .

Explanation

In the above program, we created LinqDemo class that contains the Main() method. In the Main() method we created an array of integers and then calculate the sum of all array elements using the Aggregate() method and then print the sum on the console screen. 

To use the Aggregate() method, it is mandatory to import "System.Linq" namespace.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.