Advertisement
Advanced C#, LINQ

How does LINQ's Aggregate() method work, and how would you use it to implement a custom reduction not covered by Sum()/Average()/Count()?

Short answer

Aggregate() applies an accumulator function CUMULATIVELY across a sequence, carrying forward a running result from each step to the next — useful for custom reductions (like building a concatenated string, computing a running maximum with extra logic, or a custom fold) that…

Save C# mock interview
Advertisement
AModel answer
Aggregate() applies an accumulator function CUMULATIVELY across a sequence, carrying forward a running result from each step to the next — useful for custom reductions (like building a concatenated string, computing a running maximum with extra logic, or a custom fold) that don't match any of LINQ's specific built-in aggregate methods.
var words = new[] { "Hello", "World", "LINQ" };
string sentence = words.Aggregate((acc, word) => acc + " " + word);
// "Hello World LINQ"

int product = new[] { 1, 2, 3, 4 }.Aggregate(1, (acc, n) => acc * n); // 24, with a seed value
Real-world example
Implementing a custom reduction, like computing a running maximum-so-far or concatenating a list into a single formatted string.
Likely follow-ups
  • What's the difference between the overload of Aggregate() with a seed value versus the one without?
Related topics