C# How to Convert Dictionary to List with Examples
dictionary.ToList() to get a list of key-value pairs or by selecting keys or values with dictionary.Keys.ToList() or dictionary.Values.ToList().Examples
How to Think About It
ToList() or select keys or values and convert them to a list.Algorithm
Code
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var dict = new Dictionary<string, int> { {"apple", 1}, {"banana", 2} }; var listPairs = dict.ToList(); var listKeys = dict.Keys.ToList(); var listValues = dict.Values.ToList(); Console.WriteLine("List of KeyValuePairs:"); foreach (var kvp in listPairs) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } Console.WriteLine("List of Keys:"); listKeys.ForEach(Console.WriteLine); Console.WriteLine("List of Values:"); listValues.ForEach(Console.WriteLine); } }
Dry Run
Let's trace converting a dictionary {"apple":1, "banana":2} to a list of key-value pairs.
Start with dictionary
{"apple": 1, "banana": 2}
Call ToList() on dictionary
List contains KeyValuePair("apple", 1) and KeyValuePair("banana", 2)
Resulting list
[KeyValuePair("apple", 1), KeyValuePair("banana", 2)]
| Iteration | Key | Value | List Item |
|---|---|---|---|
| 1 | apple | 1 | KeyValuePair("apple", 1) |
| 2 | banana | 2 | KeyValuePair("banana", 2) |
Why This Works
Step 1: Dictionary to List Conversion
Using ToList() on a dictionary converts it into a list of KeyValuePair objects, preserving keys and values.
Step 2: Keys or Values Only
You can convert just the keys or just the values to a list by calling Keys.ToList() or Values.ToList() respectively.
Step 3: Resulting List Type
The resulting list type depends on what you convert: a list of KeyValuePair for the whole dictionary, or list of keys or values.
Alternative Approaches
var list = dict.Select(kvp => kvp.Key + ":" + kvp.Value).ToList();
var list = new List<KeyValuePair<string, int>>(); foreach(var kvp in dict) { list.Add(kvp); }
Complexity: O(n) time, O(n) space
Time Complexity
Converting a dictionary to a list requires visiting each element once, so it takes linear time proportional to the number of items.
Space Complexity
A new list is created to hold all elements, so space used grows linearly with the dictionary size.
Which Approach is Fastest?
Using ToList() is the fastest and simplest method; manual iteration is slower and more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| dictionary.ToList() | O(n) | O(n) | Quick conversion to list of pairs |
| Keys.ToList() or Values.ToList() | O(n) | O(n) | Getting only keys or values as list |
| LINQ Select with custom projection | O(n) | O(n) | Creating custom list formats |
| Manual iteration and add | O(n) | O(n) | Adding extra processing during conversion |
dictionary.ToList() to quickly get a list of key-value pairs without extra code.ToList() causes errors.