Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Aggregates and deferred execution

โญ beginnerโณ 14 min read๐Ÿ“ Lesson 60 of 85

Count/Sum/Min/Max/Average/Any/All collapse sequences to answers โ€” and queries run when you look, not when you write.

The collapse methods

var nums = new[] { 3, 1, 4, 1, 5 };
nums.Count();          // 5
nums.Sum();            // 14
nums.Min(); nums.Max(); // 1, 5
nums.Average();        // 2.8
nums.Any(n => n > 4);  // true  โ€” "at least one"
nums.All(n => n > 0);  // true  โ€” "every one"

Any/All are predicates over the whole set; Count() with a predicate counts matches. On empty sequences Min/Max/Average throw InvalidOperationException โ€” guard or use FirstOrDefault-style handling.

Deferred execution

var query = nums.Where(n => n > 2);   // NOTHING runs yet
nums.Add(10);
foreach (var n in query) ...          // NOW it runs โ€” and sees the 10!

A query is a recipe, not a result. It executes when enumerated โ€” foreach, ToList(), an aggregate like Sum(). Each enumeration re-runs it. Pin a snapshot when the source might change: var pinned = query.ToList();.

First-or-default family:

nums.FirstOrDefault(n => n > 100);    // 0 (int default) โ€” no throw
nums.First(n => n > 100);             // throws InvalidOperationException

...OrDefault returns the type's default instead of throwing โ€” the polite variant for "might not exist".

โšก Now practice

Ready to Code
LINQ workoutFilters, projections, orderings, groupings, aggregates โ€” pipelines under discriminating tests.
4 challenges ยท ยท ~40 min