C# LINQ Aggregate — Complete Guide
In this tutorial, you'll learn about C# LINQ Aggregate. We cover key concepts, practical examples, and best practices.
You need to combine all elements of a sequence into a single value — concatenating strings, multiplying numbers, or building a comma-separated list. You write a loop with an accumulator variable. The LINQ Aggregate method encapsulates this pattern.
Wrong
var numbers = new[] { 1, 2, 3, 4, 5 };
var product = 1;
foreach (var n in numbers)
{
product *= n;
}
Output: 120 — works, but uses mutable state and multiple lines.
Right
var numbers = new[] { 1, 2, 3, 4, 5 };
var product = numbers.Aggregate(1, (acc, n) => acc * n);
Output: 120. The seed 1 is the initial accumulator. The lambda (acc, n) => acc * n runs for each element.
Without a seed, the first element becomes the initial accumulator:
var product = numbers.Aggregate((acc, n) => acc * n);
// Same result: 120
Practical example — building a CSV line:
var words = new[] { "apple", "banana", "cherry" };
var csv = words.Aggregate((acc, w) => $"{acc},{w}");
// "apple,banana,cherry"
Prevention
- Use
Aggregatefor custom accumulations not covered bySum,Count,Min,Max. - Use
Aggregatewith a seed for type-safe accumulation (seed can differ from element type). - Use
Aggregatewithout seed when the result is the same type as elements. - Use
string.Joininstead ofAggregatefor string concatenation — it is more efficient. - Use
AggregatewithIQueryablefor SQL translation (supported by EF Core for simple operations). - Avoid
Aggregatewhen readability suffers — aforeachloop is sometimes clearer.
Common Mistakes with linq aggregate
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Aggregate is used in DodaZIP for computing checksums across archive entries. For more LINQ, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro