C# How to Convert List to Dictionary Easily
ToDictionary like this: var dict = list.ToDictionary(item => item.KeyProperty, item => item.ValueProperty); where you specify how to get keys and values from list items.Examples
How to Think About It
Algorithm
Code
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var fruits = new List<string> { "apple", "banana", "cherry" }; var dict = fruits.ToDictionary(f => f[0], f => f); foreach (var kvp in dict) Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } }
Dry Run
Let's trace converting the list ["apple", "banana", "cherry"] to a dictionary using the first letter as key and the whole string as value.
Start with list
["apple", "banana", "cherry"]
Extract key and value for each item
Keys: 'a', 'b', 'c'; Values: "apple", "banana", "cherry"
Add to dictionary
{'a': "apple", 'b': "banana", 'c': "cherry"}
| Key | Value |
|---|---|
| a | apple |
| b | banana |
| c | cherry |
Why This Works
Step 1: Use ToDictionary method
The ToDictionary method converts a list to a dictionary by specifying how to get keys and values from each item.
Step 2: Specify key selector
You provide a function like item => item.KeyProperty to tell which part of the item becomes the dictionary key.
Step 3: Specify value selector
You provide a function like item => item.ValueProperty to tell which part of the item becomes the dictionary value.
Alternative Approaches
var dict = new Dictionary<char, string>(); foreach (var f in fruits) { dict[f[0]] = f; }
var lookup = fruits.ToLookup(f => f[0]); var dict = lookup.ToDictionary(g => g.Key, g => g.First());
Complexity: O(n) time, O(n) space
Time Complexity
The method loops through all list items once, so time grows linearly with list size.
Space Complexity
A new dictionary is created with one entry per list item, so space grows linearly.
Which Approach is Fastest?
Using ToDictionary is usually fastest and cleanest; manual loops are similar but more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| ToDictionary | O(n) | O(n) | Simple, readable, fast |
| Manual loop | O(n) | O(n) | Beginners or no LINQ |
| ToLookup then ToDictionary | O(n) | O(n) | Handling duplicate keys gracefully |
ToDictionary with key and value selectors to convert lists quickly and clearly.