Roadmap › LINQ — Language Integrated Query › Module: Grouping, Joins and Aggregation
Lessons in this course (12)
7. Aggregation and SelectMany
Intermediate★ Must knowLesson 7 of 12
csharp
int count = products.Count(p => p.Stock > 0);
decimal total = products.Sum(p => p.Price);
decimal avg = products.Average(p => p.Price);
decimal max = products.Max(p => p.Price); // value
Product priciest = products.MaxBy(p => p.Price)!; // element (.NET 6)
// Aggregate = fold/reduce
string csv = products.Select(p => p.Name).Aggregate((a, b) => a + "," + b);
int factorial = Enumerable.Range(1, 5).Aggregate(1, (acc, n) => acc * n); // 120
// SelectMany flattens nested collections
var allLines = orders.SelectMany(o => o.Lines); // IEnumerable<Line>
var tags = posts.SelectMany(p => p.Tags).Distinct();
var pairs = customers.SelectMany(c => c.Orders, (c, o) => new { c.Name, o.Id });Select → one output per input (can produce IEnumerable<IEnumerable<T>>); SelectMany → flattens to IEnumerable<T>.