Aggregation and grouping
Aggregation and grouping
Aggregation summarizes a sequence into a value, while grouping partitions items by a key for further analysis. Choose the operator by its contract: count items, total quantities, test existence, or require a particular number of matches. Empty input and duplicate matches matter.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Count, total and test
Count returns the number of items; Sum totals numeric values. Any tests whether at least one match exists, and All tests whether every item satisfies a condition. Any and All may stop early; All is true on an empty sequence because no item violates the condition.
using System;using System.Linq;int[] quantities = { 0, 4, 6 };Console.WriteLine(quantities.Count(n => n > 0));Console.WriteLine(quantities.Sum());Console.WriteLine(quantities.Any(n => n == 0));Console.WriteLine(Array.Empty<int>().All(n => n > 0));Console.WriteLine(Array.Empty<int>().Sum());Two entries are positive and total stock is 10. There is a zero entry. Empty All is true and integer Sum returns zero.
Expected output (reasoned, not executed):
210TrueTrue0Group before summarizing
GroupBy creates groups keyed by a selector. Each group exposes Key and can itself be enumerated. Here category identifiers use ordinal comparison for equality and result sorting; the group summaries are independent of input row ordering.
using System;using System.Linq;var sales = new[] { (Category: "Art", Units: 3), (Category: "Math", Units: 5), (Category: "Art", Units: 2) };var groups = sales.GroupBy(s => s.Category, StringComparer.Ordinal) .OrderBy(g => g.Key, StringComparer.Ordinal);foreach (var group in groups) Console.WriteLine($"{group.Key}: {group.Sum(s => s.Units)} ({group.Count()} rows)");Art contains two rows whose units total 5. Math contains one row. Grouping by category does not itself compute the total.
Expected output (reasoned, not executed):
Art: 5 (2 rows)Math: 5 (1 rows)Choose element operators and reductions
First requires at least one item; Single requires exactly one. FirstOrDefault and SingleOrDefault return a default for no match, but SingleOrDefault still rejects multiple matches. For int the ordinary default is zero; use an explicit fallback when zero is valid. Aggregate combines elements using a running accumulator; a seed defines the result for empty input.
using System;using System.Linq;int[] values = { 2, 3, 4 };Console.WriteLine(values.First(n => n > 2));Console.WriteLine(values.Single(n => n == 4));Console.WriteLine(values.FirstOrDefault(n => n > 9, -1));Console.WriteLine(values.Aggregate(1, (product, n) => product * n));Console.WriteLine(Array.Empty<int>().Aggregate(1, (product, n) => product * n));try { Console.WriteLine(values.Single(n => n > 2)); }catch (InvalidOperationException) { Console.WriteLine("multiple matches"); }First picks the earliest match, Single checks uniqueness, and the fallback distinguishes no match. The seeded reduction multiplies all values; the empty input returns its seed.
Expected output (reasoned, not executed):
34-1241multiple matchesCommon mistakes and edge cases
Do not replace Any with Count() > 0 when only existence matters. FirstOrDefault is not proof of uniqueness and default values can be real data. For non-nullable numeric values Average on empty input throws; Sum has a zero result for the integer overload. Some numeric aggregations can overflow; choose types and limits deliberately. Grouping needs storage for groups, and the examples do not assert database behavior.
Practice and recap
Use sales (Art,2), (Science,0), (Art,4), (Science,3). Report category totals in ordinal key order, count rows with positive units, and check if every row is positive. Repeat on empty input.
Hint: Group by category, Sum units, then use Count(predicate) and All(predicate).
Learning objective: Choose Count, Sum or grouping with empty-input care. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Aggregation and grouping — knowledge check
Apply the lesson concepts to the following scenarios.
What is All(n => n > 0) for an empty int array?
What does integer Sum return for an empty array?
What is group.Key?
What happens when Single finds two matches?
What does seeded Aggregate return on empty input?