Convert Dictionary to a List in C#
This post will discuss how to convert a Dictionary<TKey,TValue> to a List<T> in C#.
The LINQ’s Select() method transforms each element of a sequence into a new form. The following code example demonstrates how we can use Select() to project over elements of a dictionary and get a list of its keys.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 5} }; List<string> keys = dict.Select(kvp => kvp.Key).ToList(); Console.WriteLine(String.Join(", ", keys)); // A, B, C, D, E } } |
To get a list of its values, use Dictionary<TKey,TValue>.Values property instead. You can skip using the Select() method using the following snippet:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 5} }; List<string> keys = dict.Keys.ToList(); Console.WriteLine(String.Join(", ", keys)); // A, B, C, D, E } } |
Alternatively, if you need a list of key-value pairs, you can directly invoke the ToList() method on your dictionary instance.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 5} }; List<KeyValuePair<string, int>> keys = dict.ToList(); Console.WriteLine(String.Join(", ", keys)); } } |
Output:
[A, 1], [B, 2], [C, 3], [D, 4], [E, 5]
That’s all about converting Dictionary<TKey,TValue> to a List<T> in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)