LINQ Interview Question #126
What is Aggregate in LINQ and when would you use it?
Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
Aggregate applies an accumulator function across a sequence to produce a single result. It is similar to a fold or reduce operation in functional programming.
Detailed Explanation
Aggregate applies an accumulator function across a sequence to produce a single result. It is similar to a fold or reduce operation in functional programming.
Use Aggregate when the required accumulation is not already expressed more clearly by a specialized operator such as Sum, Count, Min, or Max. Overloads can accept a seed value and a final result selector.
Code Example
var numbers = new[] { 1, 2, 3, 4 };
int product = numbers.Aggregate(
1,
(current, next) => current * next);
// 24