0Pricing
C# Academy · Lesson

Materialization (ToList, ToDictionary) & perf notes

Turn deferred queries into concrete collections with ToList/ToArray/ToDictionary; avoid repeated enumeration and know key-uniqueness rules.

Materialization (ToList, ToDictionary) & perf notes is a free C# Academy lesson on CoddyKit — lesson 2 of 3. 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 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why materialize

Deferred queries run each time you enumerate.

  • Materialize to take a snapshot
  • Avoid multiple re-runs of expensive queries
  • Choose List, Array, or Dictionary for the job

ToList / ToArray

ToList/ToArray run the query once and store results; later source changes are not reflected.

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

public class Program
{
  public static void Main(string[] args)
  {
    List<int> data = new List<int>(new int[] { 1, 2, 3, 4 });

    var evensQuery = data.Where(x => x % 2 == 0);
    int[] evensArray = evensQuery.ToArray(); // snapshot now
    List<int> evensList = evensQuery.ToList(); // snapshot now

    data.Add(6); // changes after materialization

    Console.WriteLine("Array:");
    foreach (int x in evensArray) Console.WriteLine(x); // 2,4
    Console.WriteLine("List:");
    foreach (int x in evensList) Console.WriteLine(x);  // 2,4
  }
}

ToDictionary basics

ToDictionary materializes to a Dictionary<K,V>. Keys must be unique, otherwise it throws.

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

public sealed class City
{
  public string Name;
  public int Population;
  public City(string name, int pop){ Name = name; Population = pop; }
}

public class Program
{
  public static void Main(string[] args)
  {
    var cities = new City[]
    {
      new City("Oslo", 634000),
      new City("Rome", 2873000),
      new City("Riga", 605000)
    };

    Dictionary<string, int> byName = cities
      .ToDictionary(c => c.Name, c => c.Population);

    Console.WriteLine(byName["Rome"]); // 2873000
  }
}

Duplicates: ToLookup/GroupBy

When keys can repeat, prefer ToLookup (multi-value dictionary) or GroupBy instead of ToDictionary.

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

public sealed class Item { public string Category; public string Name; public Item(string c, string n){ Category=c; Name=n; } }

public class Program
{
  public static void Main(string[] args)
  {
    var items = new Item[]
    {
      new Item("Food","Apple"),
      new Item("Food","Bread"),
      new Item("Tool","Hammer"),
      new Item("Tool","Wrench")
    };

    // If keys may repeat, use ToLookup (multi-value) or GroupBy
    var lookup = items.ToLookup(i => i.Category, i => i.Name);

    foreach (var g in lookup)
    {
      Console.WriteLine(g.Key + ":");
      foreach (var name in g) Console.WriteLine(" - " + name);
    }
  }
}

Avoid multiple enumeration

Each enumeration can re-run work. Materialize once (e.g., ToList) when you will iterate multiple times.

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

public static class Expensive
{
  public static IEnumerable<int> Numbers()
  {
    // Simulate expensive enumeration (prints when enumerated)
    for (int i = 1; i <= 3; i++)
    {
      Console.WriteLine("Produce " + i);
      yield return i;
    }
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    var query = Expensive.Numbers().Select(x => x * x);

    Console.WriteLine("First pass:");
    foreach (int x in query) Console.WriteLine(x);

    Console.WriteLine("Second pass (re-enumerates work):");
    foreach (int x in query) Console.WriteLine(x);

    Console.WriteLine("Cache with ToList:");
    List<int> cached = query.ToList(); // runs once
    foreach (int x in cached) Console.WriteLine(x); // no extra production logs
  }
}

Materialization checklist

Checklist:

  • Use ToList/ToArray to snapshot.
  • Use ToDictionary when keys are unique; else ToLookup/GroupBy.
  • Avoid multiple enumeration of expensive sources; cache once.
  • Materialize near boundaries (I/O, DB calls) for predictable behavior.

ToDictionary requirement

Quick check: What must be true when using ToDictionary(keySelector) on a sequence?

Recap

Recap: Materialize with ToList/ToArray for snapshots, ToDictionary for fast lookup (unique keys), and cache to avoid re-running expensive queries.

Frequently asked questions

Is the “Materialization (ToList, ToDictionary) & perf notes” lesson free?

Yes — the full text of “Materialization (ToList, ToDictionary) & perf notes” is free to read here on the web, and the C# Academy course includes 3 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 “Materialization (ToList, ToDictionary) & perf notes”?

Turn deferred queries into concrete collections with ToList/ToArray/ToDictionary; avoid repeated enumeration and know key-uniqueness rules. 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 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Materialization (ToList, ToDictionary) & perf notes” 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. GroupBy, Join, Aggregate, projections (anonymous types)
  2. Materialization (ToList, ToDictionary) & perf notes
  3. Composability tips
← Back to C# Academy