This post will discuss how to convert Dictionary<TKey,TValue> values to an Array in C#.

1. Using Dictionary<TKey,TValue>.Values Property

The Dictionary<TKey,TValue>.Values property to returns a collection containing dictionary’s values. The idea is to allocate an array to accommodate all the values of the dictionary, and then use the CopyTo() method to copy values from the dictionary to the array. The following code example demonstrates this:

Download  Run Code

 
Alternatively, you can use the ToArray() method to convert the collection returned by the Value property into an array. Note that the ToArray() method requires LINQ and you will need to include System.Linq namespace.

Download  Run Code

 
If you are not allowed to use LINQ, you can store values in a List<T> using its constructor.

Download  Run Code

 
If you particularly need an array, you can call the ToArray() method on the list. However, this creates an intermediate list object and should be avoided.

Download  Run Code

2. Using Enumerable.Select() Method

The Select() method from LINQ 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 an array of its values.

Download  Run Code

 
The Select() method can be used to transform the dictionary into an array of strings, containing key-value pairs, as shown below:

Download  Run Code

That’s all about converting Dictionary<TKey,TValue> values to an Array in C#.