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 = 466Approach:
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:
Output:
Sum is : 166