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.

Download  Run Code

 
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.

Download  Run Code

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:

Download  Run Code

 
Alternatively to get the list of values present in the Dictionary<TKey,TValue>, you can use the Dictionary<TKey,TValue>.Value property.

Download  Run Code

That’s all about getting a List of keys and values in a Dictionary in C#.