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
- Key and value selectors shape the dictionary in one call.
- Lookups after that are constant time, no re-enumeration.
ContainsKeyanswers the missing-planet question safely.
Keywords and builtins used here
newvar
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.
Step 1 of 3 in Materializing & sets, step 13 of 17 in LINQ in depth.