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:
- 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#
using System;
using System.Linq;
class GFG{
static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 14, 5, 26, 7, 8, 90, 10};
int sum = 0;
sum = arr.Aggregate((element1, element2) => element1 + element2);
Console.Write( "Sum is : " + sum);
}
}
|
Output:
Sum is : 166
Last Updated :
09 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...