typestar

ToDictionary in C#

Materialize a query into the collection you will actually use.

var planets = new[] { (Name: "Mercury", Au: 0.39), (Name: "Mars", Au: 1.52) };

var byName = planets.ToDictionary(p => p.Name, p => p.Au);
Console.WriteLine(byName["Mars"]);

// materializing runs the query once; reusing the result is free
var index = Enumerable.Range(0, 5).ToDictionary(i => i, i => i * i);
Console.WriteLine(index[4]);
Console.WriteLine(byName.ContainsKey("Pluto"));

How it works

  1. Key and value selectors shape the dictionary in one call.
  2. Lookups after that are constant time, no re-enumeration.
  3. ContainsKey answers the missing-planet question safely.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
385
Tokens
106
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 1 of 3 in Materializing & sets, step 13 of 17 in LINQ in depth.

← Previous Next →