C# · Lesson 3

Collections & LINQ

List, Dictionary, HashSet and arrays, IEnumerable and deferred execution, LINQ (Where, Select, GroupBy, OrderBy, Join, Aggregate, ToDictionary, DistinctBy, Chunk) in method and query syntax, the multiple-enumeration trap, and how it all maps to TypeScript array methods.

12 min read

In short

  • List, Dictionary, HashSet: arrays, maps and sets
  • A missing key throws: use TryGetValue
  • Where is filter, Select is map, FirstOrDefault is find
  • Queries are recipes: they run when enumerated
  • Materialize once with ToList() when you reuse results

Most business code is collections: the orders for a customer, the rows of a report, the messages in a batch. In TypeScript you have one workhorse, the array, plus Map and Set. .NET has a family of collection types and one query language that works over all of them: LINQ (Language Integrated Query). You'll read LINQ in nearly every file of a .NET codebase, from in-memory reports to EF Core queries that become SQL.

The biggest mental shift from TypeScript: array.filter(...).map(...) runs immediately and builds new arrays at each step. LINQ's Where(...).Select(...) builds a recipe that runs later, one item at a time, when someone enumerates it. Most LINQ surprises come from forgetting that.

The collection types

▶ Try
var names = new List<string> { "Ada", "Grace" };   // like a TS array: grows and shrinks
names.Add("Linus");
names.Insert(0, "Alan");
names.Remove("Grace");
Console.WriteLine($"{names.Count}: {string.Join(", ", names)} (index of Linus: {names.IndexOf("Linus")})");

var stock = new Dictionary<string, int>             // like a Map<string, number>
{
    ["apple"] = 3,
    ["pear"] = 0,
};
stock["kiwi"] = 7;                    // add or overwrite
stock["apple"] += 2;                  // read, then write
Console.WriteLine(stock["apple"]);    // 5
Console.WriteLine(stock.ContainsKey("plum"));                       // False
Console.WriteLine(stock.TryGetValue("plum", out var plums) ? plums : -1);  // -1
Console.WriteLine(stock.GetValueOrDefault("plum"));                 // 0

var tags = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "urgent", "b2b" };
Console.WriteLine(tags.Add("URGENT"));   // False: already there (ignoring case)
Console.WriteLine(tags.Contains("B2B")); // True
TypeScriptC#Notes
T[]List<T>Add, Insert, Remove, RemoveAt, Count, Contains, IndexOf, Sort
fixed T[]T[]fixed length, Length instead of Count
Map<K, V>Dictionary<TKey, TValue>dict[key], TryGetValue, ContainsKey, Remove, Keys, Values
Set<T>HashSet<T>Add returns false for duplicates; UnionWith, IntersectWith, ExceptWith
Queue<T>, Stack<T>, LinkedList<T>, SortedDictionary<TKey, TValue>, PriorityQueue<TElement, TPriority>

The important differences from JavaScript:

  • A missing key throws. stock["plum"] throws KeyNotFoundException. There's no undefined. Use TryGetValue when a key might be missing, or GetValueOrDefault.
  • Add on a dictionary throws for a duplicate key. dict[key] = value inserts or overwrites.
  • Keys use Equals and GetHashCode, so records, tuples and strings work as keys by value. For strings you can pass a comparer: new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase).
  • Iteration order: List<T> and arrays keep order. Dictionary and HashSet happen to enumerate in insertion order while you only add, but that isn't guaranteed. Sort when order matters.

Collection expressions and spreads (C# 12)

▶ Try
int[] a = [1, 2, 3];
List<int> b = [4, 5];
int[] all = [..a, ..b, 6];             // spread, like [...a, ...b, 6]
IReadOnlyList<string> empty = [];
Console.WriteLine($"{string.Join(",", all)} {empty.Count}");

Read-only interfaces

Method signatures usually take and return interfaces, not concrete types:

  • IEnumerable<T>: "something I can loop over". The most general, and what LINQ works on. Don't assume you can loop over it twice, or that it's cheap to do so.
  • IReadOnlyCollection<T>: adds Count. IReadOnlyList<T>: adds an indexer.
  • IReadOnlyDictionary<TKey, TValue>, IReadOnlySet<T>: read-only views of the others.
  • ICollection<T>, IList<T>, IDictionary<TKey, TValue>: the mutable versions.

A good default: accept the most general type you need (IEnumerable<T>), and return something specific and read-only (IReadOnlyList<T>) so callers know they get a materialized list.

IEnumerable and yield return

IEnumerable<T> is .NET's iterable, the equivalent of Iterable<T> in TypeScript. foreach asks it for an enumerator and calls MoveNext() until it returns false. A method with yield return is a generator: it runs lazily, one item per MoveNext().

▶ Try
foreach (var n in Countdown(3)) Console.WriteLine($"got {n}");

static IEnumerable<int> Countdown(int from)
{
    for (int i = from; i > 0; i--)
    {
        Console.WriteLine($"  producing {i}");
        yield return i;               // pause here until the caller asks for the next item
    }
}
▶ Try
function* countdown(from: number) {
  for (let i = from; i > 0; i--) {
    console.log(`  producing ${i}`);
    yield i;
  }
}
for (const n of countdown(3)) console.log(`got ${n}`);

The output interleaves producing and got: nothing is computed ahead of time. Calling Countdown(3) on its own doesn't even start the method. It only runs when someone enumerates it.

LINQ: the TypeScript array methods, lazily

▶ Try
var orders = new List<Order>
{
    new(1, "ada", 120m, "paid"),
    new(2, "grace", 45m, "pending"),
    new(3, "ada", 80m, "paid"),
    new(4, "linus", 300m, "refunded"),
};

var paidByCustomer = orders
    .Where(o => o.Status == "paid")                     // filter
    .GroupBy(o => o.Customer)                            // group into (key, items)
    .Select(g => new { Customer = g.Key, Total = g.Sum(o => o.Total) })   // map
    .OrderByDescending(x => x.Total)                     // sort, like toSorted(): the source is untouched
    .ToList();                                           // run it now and keep the results

foreach (var row in paidByCustomer) Console.WriteLine($"{row.Customer}: {row.Total}");
Console.WriteLine(orders.Any(o => o.Status == "refunded"));          // some
Console.WriteLine(orders.All(o => o.Total > 0));                     // every
Console.WriteLine(orders.First(o => o.Total > 100).Id);              // find (throws if none)
Console.WriteLine(orders.FirstOrDefault(o => o.Total > 1000)?.Id ?? -1);   // find, or null
Console.WriteLine(orders.Sum(o => o.Total));
Console.WriteLine(orders.MaxBy(o => o.Total)!.Customer);

public record Order(int Id, string Customer, decimal Total, string Status);
TypeScriptLINQNotes
filterWhere
mapSelectSelect((x, i) => ...) gives the index too
flatMapSelectMany
reduceAggregateusually you want Sum, Count, Min, Max, Average instead
findFirst / FirstOrDefaultFirst throws on no match, FirstOrDefault returns default (null, 0)
some / everyAny / All
includesContains
toSorted((a, b) => ...)OrderBy(x => key), ThenBy, OrderByDescendingstable, never mutates the source
sliceSkip, Takealso TakeWhile, SkipWhile, TakeLast
Object.groupByGroupBy, ToLookupgroups keep the order of first appearance
new Map(xs.map(...))ToDictionary(x => key, x => value)throws on a duplicate key
[...new Set(xs)]Distinct(), DistinctBy(x => key)
(lodash chunk)Chunk(size)batches as arrays
(lodash zip)Zip
length after filterCount(predicate)

Deferred execution

Operators like Where, Select, OrderBy and GroupBy don't do anything when you call them. They return a query object, and the work happens when you enumerate it: in a foreach, or by calling an operator that needs the results (ToList, ToArray, ToDictionary, Count, Sum, First, Any...).

▶ Try
var numbers = new List<int> { 1, 2, 3 };
var big = numbers.Where(n => n > 1);     // nothing has run yet
numbers.Add(4);
Console.WriteLine(big.Count());          // 3: the query runs now and sees the 4

int threshold = 2;
var overThreshold = numbers.Where(n => n > threshold);
threshold = 3;                           // the lambda captured the variable, not its value
Console.WriteLine(string.Join(",", overThreshold));   // 4

var snapshot = numbers.Where(n => n > 1).ToList();    // runs once, now
numbers.Add(5);
Console.WriteLine(snapshot.Count);       // still 3

Deferred execution is a feature: queries compose without building intermediate lists, First() stops reading as soon as it finds a match, and an EF Core query becomes one SQL statement. But it means a query re-runs every time you enumerate it, with whatever the source and captured variables hold at that moment.

The multiple enumeration trap

▶ Try
int calls = 0;
var expensive = Ids().Select(id => { calls++; return id * 10; });

if (expensive.Any())                          // enumerates (stops after the first item)
    Console.WriteLine(expensive.Count());     // enumerates everything again
foreach (var x in expensive) { }              // and again
Console.WriteLine($"selector ran {calls} times for 3 items");

static IEnumerable<int> Ids() { yield return 1; yield return 2; yield return 3; }

Every enumeration runs the whole pipeline again. If the source is a database query, an HTTP call, a file being read or a generator with side effects, that's repeated work or, worse, different results each time. Some sources can only be enumerated once (a network stream, a DbDataReader). The fix is simple: materialize once with ToList() or ToArray() when you need the results more than once. Rider and the .NET analyzers flag "possible multiple enumeration of IEnumerable" for this reason.

The opposite mistake is calling ToList() after every step "to be safe". It allocates a list per step and loses the laziness. Materialize at the end, or where you need a stable snapshot.

Grouping, joining and building dictionaries

▶ Try
string[] words = ["apple", "avocado", "banana", "blueberry", "cherry", "apricot"];

var byLetter = words
    .GroupBy(w => w[0])
    .ToDictionary(g => g.Key, g => g.Count());
Console.WriteLine(string.Join(" ", byLetter.Select(kv => $"{kv.Key}={kv.Value}")));

var customers = new[] { new Customer("c1", "Ada"), new Customer("c2", "Grace"), new Customer("c3", "Linus") };
var invoices = new[] { new Invoice("c1", 100m), new Invoice("c1", 50m), new Invoice("c2", 70m) };

// Inner join: one result per matching pair (Linus has no invoices, so he's left out).
var pairs = customers.Join(invoices, c => c.Id, i => i.CustomerId, (c, i) => $"{c.Name}:{i.Amount}");
Console.WriteLine(string.Join(" ", pairs));

// Left join: every customer with their (possibly empty) group of invoices.
var totals = customers.GroupJoin(invoices, c => c.Id, i => i.CustomerId,
    (c, invs) => $"{c.Name}={invs.Sum(i => i.Amount)}");
Console.WriteLine(string.Join(" ", totals));

// A lookup is a dictionary of groups that returns an empty group for a missing key.
var invoicesByCustomer = invoices.ToLookup(i => i.CustomerId);
Console.WriteLine(invoicesByCustomer["c3"].Count());   // 0, no exception

// Batches and distinct-by-key.
foreach (var batch in Enumerable.Range(1, 7).Chunk(3)) Console.Write($"[{string.Join(",", batch)}] ");
Console.WriteLine();
Console.WriteLine(string.Join(",", invoices.DistinctBy(i => i.CustomerId).Select(i => i.Amount)));
Console.WriteLine(Enumerable.Range(1, 5).Aggregate(1, (product, n) => product * n));   // 120

public record Customer(string Id, string Name);
public record Invoice(string CustomerId, decimal Amount);
  • GroupBy returns IGrouping<TKey, TElement>: a Key plus the items. Groups come out in the order their keys first appear.
  • ToDictionary throws ArgumentException on a duplicate key. If keys can repeat, group first or use ToLookup.
  • Join is an inner join and GroupJoin is the building block for a left join. For in-memory data, a ToDictionary or ToLookup on one side plus a Select on the other is often clearer.
  • Chunk(100) is how you batch work: 100 ids per database query, 100 messages per message-queue batch.

Query syntax

LINQ also has a SQL-like syntax. The compiler turns it into the same method calls:

▶ Try
var people = new[] { new Person("Ada", "London", 36), new Person("Grace", "New York", 45), new Person("Alan", "London", 41) };

var query =
    from p in people
    where p.Age > 35
    let initial = p.Name[0]
    orderby p.City, p.Name
    select $"{p.City}: {p.Name} ({initial})";

foreach (var line in query) Console.WriteLine(line);

var byCity = from p in people
             group p by p.City into g
             select new { City = g.Key, Count = g.Count() };
foreach (var row in byCity) Console.WriteLine($"{row.City} {row.Count}");

public record Person(string Name, string City, int Age);

Most teams use method syntax for everyday code. Query syntax reads better with join and let (intermediate values), and you'll see it in older EF code. Both mix freely: (from p in people select p.Age).Max().

LINQ to EF Core: IQueryable

The same operators work on EF Core's DbSet<T>, but there they build an expression tree that EF Core translates to SQL:

// EF Core (not runnable here)
var topCustomers = await db.Orders
    .Where(o => o.Status == OrderStatus.Paid && o.CreatedAt >= since)   // becomes WHERE ...
    .GroupBy(o => o.CustomerId)
    .Select(g => new { CustomerId = g.Key, Total = g.Sum(o => o.Total) })
    .OrderByDescending(x => x.Total)
    .Take(10)                                                             // becomes TOP/LIMIT 10
    .ToListAsync(ct);                                                     // the query runs here

var wrong = db.Orders.AsEnumerable().Where(o => o.Total > 100);   // loads EVERY order, then filters in memory
  • IQueryable<T> is translated to SQL. IEnumerable<T> runs in your process. Calling AsEnumerable(), ToList(), or passing the query to a method that takes IEnumerable<T> switches from the database to memory, and everything after it runs on all the rows that came back.
  • Only things EF can translate are allowed in the lambdas. Calling your own C# method in a Where usually fails at runtime with "could not be translated".
  • The query runs at ToListAsync, FirstOrDefaultAsync, CountAsync and friends. Deferred execution again.

Common mistakes

  • Enumerating a query twice. Materialize with ToList() when you need the results more than once.
  • First() on something that may be empty. It throws InvalidOperationException ("Sequence contains no elements"). Use FirstOrDefault() and handle null. Same for Single, Max, Min and Average on an empty sequence of numbers. (Sum of nothing is 0.)
  • dict[key] for a key that may be missing. Use TryGetValue.
  • Changing a list while you foreach over it. List<T> throws InvalidOperationException ("Collection was modified"). Use RemoveAll(predicate), or loop over a copy (foreach (var x in list.ToList())).
  • ToDictionary with duplicate keys. It throws. Decide what a duplicate means (group, take the first, sum).
  • Count() > 0 instead of Any(). Count() may walk the whole sequence; Any() stops at the first item.
  • Side effects in Select. Because of deferred execution, they run when (and as often as) the query is enumerated. Keep lambdas pure and do side effects in a foreach.
  • OrderBy(a).OrderBy(b). That sorts by b. In memory, the first key only survives as a tie-breaker because LINQ's sort is stable, and a database query makes no such promise (EF Core keeps only the last OrderBy). Use ThenBy for a secondary key.

In a real codebase

Side note
// A minimal API endpoint (not runnable here)
app.MapGet("/reports/revenue", async (AppDbContext db, DateOnly from, DateOnly to, CancellationToken ct) =>
{
    var sales = await db.Sales
        .Where(s => s.Date >= from && s.Date <= to)
        .Select(s => new { s.Region, s.Product, Revenue = s.Units * s.UnitPrice })
        .ToListAsync(ct);                                   // one SQL query, only the needed columns

    var report = sales
        .GroupBy(s => s.Region)
        .Select(g => new RegionRevenue(g.Key, g.Sum(s => s.Revenue),
            g.GroupBy(s => s.Product).MaxBy(p => p.Sum(s => s.Revenue))!.Key))
        .OrderByDescending(r => r.Revenue)
        .ToList();                                          // in-memory LINQ for the shaping

    return Results.Ok(report);
});

Filter and project in the database, then shape in memory. That split, and knowing exactly where the query runs, is most of what "being good at LINQ" means on a .NET team.

The exercises

  1. Word frequency: Dictionary basics: counting, TryGetValue, merging without mutating inputs.
  2. Order queries: everyday LINQ one-liners: Where, Sum, Distinct, MaxBy, Any, Select.
  3. A sales report: GroupBy, OrderBy/ThenBy, projections into records and ToDictionary.
  4. A lazy log parser: yield return, deferred errors, eager argument checks and stopping early.
  5. An accounts receivable aging report: joins across three sources, partial payments and date buckets.
  6. Pagination with lookahead: an enumerator by hand: one pass, lazy, IsLast without reading ahead too far.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 10-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app