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.

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
  }
}

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