Open In App

C# Program to Calculate the Sum of Array Elements using the LINQ Aggregate() Method

Given an array of integers, now we calculate the sum of array elements. So we use the Aggregate() method of LINQ. This method applies a function to all the elements of the source sequence and calculates a cumulative result and return value. This method is overloaded in three different ways:

Example:



Input: { 34, 27, 34, 5, 6 }
Output: Sum = 106

Input: { 3, 4, 27, 34, 15, 26, 234, 123 }
Output:  Sum = 466

Approach:

1. Create and initialize an array of integer type



2. Now find the sum of the array using the Aggregate() function.

sum = arr.Aggregate((element1,element2) => element1 + element2);

3. Display the sum of the elements of the array

Example:




// C# program to finding the sum of the array elements
// using Aggregate() Method
using System;
using System.Linq;
 
class GFG{
 
static void Main(string[] args)
{
     
    // Creating and initializing the array
    // with integer values
    int[] arr = { 1, 2, 3, 14, 5, 26, 7, 8, 90, 10};
    int sum = 0;
     
    // Finding the sum of the elements of arr
    // using Aggregate() Method
    sum = arr.Aggregate((element1, element2) => element1 + element2);
     
    // Displaying the final output
    Console.Write("Sum is : " + sum);
}
}

Output:

Sum is : 166

 

Article Tags :