CKTIS / C#
Enumerable.Aggregate: practical reference
Enumerable.Aggregate: practical reference: Immediately enumerates the source and folds its elements into one value with an accumulator. The seeded overload starts from the explicit seed; the unseeded overload uses the first element.
Version: .NET LINQ; verified on .NET 10.0.14
Syntax
source.Aggregate(/* overload-specific arguments */)Immediately enumerates the source and folds its elements into one value with an accumulator. The seeded overload starts from the explicit seed; the unseeded overload uses the first element.
Use it for reductions whose next state depends on the previous state, such as building a checksum or summary object. Prefer Sum for an ordinary sum because it states the intent more clearly.
The accumulator can have side effects and is invoked sequentially; an exception stops enumeration. Enumerating a deferred source again performs the entire reduction again.
An empty sequence without a seed throws InvalidOperationException. With a seed it returns that seed without invoking the accumulator; overflow depends on the accumulator code.
The complete program actually uses Enumerable.Aggregate; its exact expected stdout is 10.
Examples
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(new[] { 1, 2, 3, 4 }.Aggregate(0, (sum, value) => sum + value));
Result
10
The complete program actually uses `Enumerable.Aggregate`; its exact expected stdout is `10`.