ToDictionary
Learn collection conversion with ToDictionary and ToList.
Materializing with ToList
The ToList method turns a deferred LINQ query into a real List<T>. When you call it, the query runs immediately and the elements are stored in memory. numbers.Where(n => n > 5).ToList() returns a List<int>.
ToList is useful when you will iterate the query multiple times or add and remove elements. If you only walk it once with foreach, skip ToList and save memory.
Materializing with ToDictionary
The ToDictionary method turns a collection into a Dictionary<K, V>. It takes a key-selector lambda: students.ToDictionary(s => s.Id). The element itself becomes the value.
You can also pass a value selector: students.ToDictionary(s => s.Id, s => s.Name). Keys must be unique; if a key repeats, an ArgumentException is thrown.
Exercise Convert to dictionary and access
Convert the students list into a Dictionary<int, Student> with ToDictionary(s => s.Id). Print the name of the student whose Id is 2 with Console.WriteLine.
Show example solution
Build the dictionary with var dict = students.ToDictionary(s => s.Id);, then Console.WriteLine(dict[2].Name);.
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;
class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main()
{
var students = new List<Student>
{
new Student { Id = 1, Name = "Ayşe" },
new Student { Id = 2, Name = "Mehmet" },
new Student { Id = 3, Name = "Zeynep" }
};
var dict = students.ToDictionary(s => s.Id);
Console.WriteLine(dict[2].Name);
}
}
Test yourself
-
Complete the ToList call
List<int> evens = numbers.Where(n => n % 2 == 0).____();Show answer
List<int> evens = numbers.Where(n => n % 2 == 0).ToList(); -
Match each method to its output
- ToList()
- List<T>
- ToArray()
- T[]
- ToDictionary(k => k)
- Dictionary<K,T>
- First()
- Single element
-
When does ToDictionary throw?
- When the same key is given twice
- On an empty collection
- On a single-element collection
- When called after ToList
Show answer
When the same key is given twice — Correct. ToDictionary throws ArgumentException when the same key is given twice. Keys must be unique.