Aggregate Method
In System.Linq namespace
Summary
Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value.
Method Signature
public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource> func);
public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func);
public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector);
Parameters
-
source: An
IEnumerable<TSource>
to aggregate over. - func: A function to iterate over each element of the sequence.
- seed: The initial accumulator value.
- resultSelector: A transform function to apply to the final accumulator value.
Returns
- TSource: The transformed accumulator value.
- TAccumulate: The transformed accumulator value.
- TResult: The transformed accumulator value.
Remarks
The Aggregate
method performs the following operations:
- Initializes the accumulator to the
seed
value. - For each element in the sequence, applies the
func
delegate to the current accumulator value and the element, and then updates the accumulator with the result. - After iterating through all elements, if
resultSelector
is provided, it applies this delegate to the final accumulator value to produce the result. Otherwise, the final accumulator value is returned.
If the source sequence is empty, Aggregate
returns the seed
value. If func
is null, an ArgumentNullException
is thrown.
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// Example 1: Sum of numbers
int sum = numbers.Aggregate(0, (current, next) => current + next);
Console.WriteLine($"Sum: {sum}"); // Output: Sum: 15
// Example 2: Concatenate numbers into a string
string concatenated = numbers.Aggregate("", (current, next) => current + next.ToString());
Console.WriteLine($"Concatenated: {concatenated}"); // Output: Concatenated: 12345
// Example 3: Using resultSelector to find the average
double average = numbers.Aggregate(0, (current, next) => current + next, total => (double)total / numbers.Count);
Console.WriteLine($"Average: {average}"); // Output: Average: 3
// Example 4: More complex aggregation (e.g., building a string with separators)
string csvString = numbers.Aggregate("Numbers: ", (current, next) => current + next + ", ", result => result.TrimEnd(','));
Console.WriteLine($"CSV String: {csvString}"); // Output: CSV String: Numbers: 1, 2, 3, 4, 5
}
}