Get List of keys and values in a Dictionary in C#
This post will discuss how to get a List of keys and values in a Dictionary in C#.
1. Using List<T> Constructor
The List<T> constructor has an overload that initializes a new instance of the List<T> class with elements of the specified collection. To get the list of keys present in the Dictionary<TKey,TValue>, you can pass the collection returned by the Dictionary<TKey,TValue>.Keys to List<T> class constructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict["A"] = 1; dict["B"] = 2; dict["C"] = 3; List<string> keys = new List<string>(dict.Keys); Console.WriteLine(String.Join(", ", keys)); // A, B, C } } |
Alternatively to get the list of values present in the Dictionary<TKey,TValue>, you can use the Dictionary<TKey,TValue>.Value property. It returns a collection containing the values, which can be passed to the List<T> constructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict["A"] = 1; dict["B"] = 2; dict["C"] = 3; List<int> values = new List<int>(dict.Values); Console.WriteLine(String.Join(", ", values)); // 1, 2, 3 } } |
2. Using ToList() Method
Starting with .NET Framework 3.5, you can use the ToList() method to convert an Enumerable<T> to a List<T>. It is available in LINQ and you need to add System.Linq namespace. For example, the following code directly calls the ToList() method on Dictionary<TKey,TValue>.Keys property to get a list of all keys:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict["A"] = 1; dict["B"] = 2; dict["C"] = 3; List<string> keys = dict.Keys.ToList(); Console.WriteLine(String.Join(", ", keys)); // A, B, C } } |
Alternatively to get the list of values present in the Dictionary<TKey,TValue>, you can use the Dictionary<TKey,TValue>.Value property.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict["A"] = 1; dict["B"] = 2; dict["C"] = 3; List<int> values = dict.Values.ToList(); Console.WriteLine(String.Join(", ", values)); // 1, 2, 3 } } |
That’s all about getting a List of keys and values in a Dictionary 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 :)