Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>): It applies an accumulator function on the specified sequence. Here, the seed value is used to define the starting accumulator value, and the function is used to select the final result value.
  • Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>): It applies an accumulator function on the specified sequence. Here, the specified seed value is used to define the starting accumulator value.
  • Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>): It applies an accumulator function on the specified sequence.

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#




// 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

 


Last Updated : 09 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads