Lesson 13/31

Tutorials LINQ Mastery

Aggregate: The 'Fold' function of .NET

On this page

Mastering the Fold

Aggregate is the 'Swiss Army Knife' of LINQ. It allows you to build a single result by processing elements one by one—similar to a 'Reduce' function in JavaScript or 'Fold' in functional programming.

1. Cumulative Operations

Imagine you want to build a comma-separated string from a list of names. You can use string.Join, or you can use Aggregate to see how the logic works under the hood.


var names = new[] { "Alice", "Bob", "Charlie" };
var result = names.Aggregate((current, next) => current + ", " + next);
// Result: "Alice, Bob, Charlie"
    

2. Aggregating with an Initial Seed

You can provide a starting value. This is powerful for complex transformations, like building a custom JSON object or calculating a complex running balance with a starting cash amount.

3. Architect Insight

Q: "When should I NOT use Aggregate?"

Architect Answer: "Don't use it for things already provided by Sum, Min, or string.Join. Aggregate is the most 'Technical' LINQ method and can be difficult for junior developers to read. Only use it when you have a truly custom accumulation logic that can't be expressed by standard operators."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

LINQ Mastery
Course syllabus
General
1. Core Foundations
2. Filtering & Transformation
3. Aggregation & Quantifiers
4. Ordering & Partitioning
5. Sets & Lookups
6. Join & Grouping
7. Advanced Providers & Parallelism
8. Real-world Performance & Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details