0Pricing
C# Academy · Lesson

Aggregates and ToList

Count, Sum, and materialize.

Aggregates and ToList is a free C# Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Counting Elements

Count returns the number of elements in a sequence. With a predicate, it counts only matching elements.

It forces enumeration, so the whole sequence is walked to produce the total — an aggregate operation.

using System;
using System.Linq;

int[] nums = { 1, 2, 3, 4, 5 };
Console.WriteLine(nums.Count());
Console.WriteLine(nums.Count(n => n > 2));

Summing Values

Sum adds up numeric values. On a numeric sequence it sums the elements; with a selector it sums a projected value from each element.

It returns the same numeric type as the source or selector result.

using System;
using System.Linq;
using System.Collections.Generic;

record Order(int Qty, decimal Price);
var orders = new List<Order> { new(2, 5m), new(3, 4m) };
decimal total = orders.Sum(o => o.Qty * o.Price);
Console.WriteLine(total);

Averaging Values

Average computes the arithmetic mean. Like Sum it accepts an optional selector.

The result is a floating-point type (for example double) even when the source is integers, so no precision is lost in the division.

using System;
using System.Linq;

int[] scores = { 80, 90, 100 };
double avg = scores.Average();
Console.WriteLine(avg);

Min and Max

Min and Max return the smallest and largest values. With a selector they reduce a projected key.

In modern .NET, MaxBy and MinBy return the whole element with the extreme key, not just the key value.

using System;
using System.Linq;
using System.Collections.Generic;

record P(string Name, int Age);
var ps = new List<P> { new("Ana", 30), new("Bo", 22) };
var oldest = ps.MaxBy(p => p.Age);
Console.WriteLine(oldest!.Name);

Empty Sequence Pitfalls

On an empty sequence, Average, Min, and Max over value types throw InvalidOperationException. Sum returns zero and Count returns zero.

Guard with Any() or use DefaultIfEmpty before averaging possibly-empty data.

using System;
using System.Linq;

int[] empty = Array.Empty<int>();
double avg = empty.DefaultIfEmpty(0).Average();
Console.WriteLine(avg);

Aggregate for Custom Folds

Aggregate folds a sequence into one value with an accumulator function. It is the general form behind Sum and others.

You can supply a seed and combine each element into a running result — useful for products, concatenations, or custom logic.

using System;
using System.Linq;

int[] nums = { 1, 2, 3, 4 };
int product = nums.Aggregate(1, (acc, n) => acc * n);
Console.WriteLine(product);

Materializing with ToList

ToList executes the query immediately and copies results into a List<T>. This breaks deferred execution on purpose.

Use it to take a stable snapshot, avoid re-running an expensive pipeline, or get list features like indexing and Count property.

using System;
using System.Linq;

int[] nums = { 1, 2, 3, 4 };
var evens = nums.Where(n => n % 2 == 0).ToList();
evens.Add(6);
Console.WriteLine(string.Join(", ", evens));

ToArray and ToDictionary

Related materializers include ToArray for a fixed-size array and ToDictionary for key-based lookup.

ToDictionary takes a key selector (and optional value selector) and throws if two elements produce the same key.

using System;
using System.Linq;
using System.Collections.Generic;

record P(string Name, int Age);
var ps = new List<P> { new("Ana", 30), new("Bo", 22) };
var byName = ps.ToDictionary(p => p.Name, p => p.Age);
Console.WriteLine(byName["Ana"]);

Why Materialize

Deferred queries re-run every time they are iterated. If a pipeline is costly or reads a changing source, that repetition causes bugs and slowness.

Calling ToList once captures the results so later reads are cheap and consistent.

using System;
using System.Linq;

int runs = 0;
int[] nums = { 1, 2, 3 };
var list = nums.Select(n => { runs++; return n; }).ToList();
foreach (var _ in list) { }
foreach (var _ in list) { }
Console.WriteLine(runs);

First, Single, and Any

Element operators also force execution. First returns the first match (throwing if none), FirstOrDefault returns a default instead, and Single demands exactly one.

Any tells you whether a sequence has any matching element without counting all of them.

using System;
using System.Linq;

int[] nums = { 3, 8, 5, 12 };
int firstBig = nums.First(n => n > 7);
bool hasOdd = nums.Any(n => n % 2 == 1);
Console.WriteLine($"{firstBig} {hasOdd}");

Full Pipeline

Real queries chain filtering, projection, sorting, and aggregation, often ending in a materializer.

Read it top-to-bottom: filter, then shape, then order, then collect. The final ToList runs the whole pipeline once.

using System;
using System.Linq;
using System.Collections.Generic;

record Sale(string City, int Amt);
var sales = new List<Sale> { new("NY", 5), new("LA", 3), new("NY", 9) };
var top = sales.Where(s => s.Amt > 4)
               .OrderByDescending(s => s.Amt)
               .Select(s => s.City)
               .ToList();
Console.WriteLine(string.Join(", ", top));

Quick Check

Reason about deferred execution and materialization.

Recap

Aggregates reduce a sequence to a value: Count, Sum, Average, Min/Max, MinBy/MaxBy, and the general Aggregate. They force execution and can throw on empty sources.

ToList, ToArray, and ToDictionary materialize results, breaking deferral so an expensive pipeline runs once. This completes the LINQ filtering-and-projecting toolkit.

Frequently asked questions

Is the “Aggregates and ToList” lesson free?

Yes — the full text of “Aggregates and ToList” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Aggregates and ToList”?

Count, Sum, and materialize. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Aggregates and ToList” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Where and Filtering
  2. Select and Projection
  3. OrderBy and Grouping
  4. Aggregates and ToList
← Back to C# Academy