LINQ Interview Question #86
What does ToDictionary do in LINQ?
Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate
Quick Interview Answer
ToDictionary materializes a sequence into a Dictionary<TKey,TValue> using a key selector and, optionally, an element selector or comparer.
Detailed Explanation
ToDictionary materializes a sequence into a Dictionary<TKey,TValue> using a key selector and, optionally, an element selector or comparer.
Dictionary keys must be unique. If duplicate keys are produced, ToDictionary throws an exception. It is appropriate when efficient key-based lookup is required.
Code Example
var byId = products.ToDictionary(
p => p.Id,
p => p.Name);
string name = byId[10];