.Net framework Dictionary<TKey, TValue> class represents a collection of keys and values. the Dictionary<TKey, TValue>.Keys property allow us to get a collection containing the keys in the Dictionary<TKey, TValue>. this Keys property value type is System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.
to convert a dictionary keys to array, first we need to get the dictionary keys by its ‘Keys’ property. this property return a collection (generic list) of dictionary keys. after getting the List<T>, we can convert it to an array by List class ToArray() method.
List<T>.ToArray() method allow us to copy the elements of the List<T> to a new array. so we can convert the dictionary keys into array as Dictionary<TKey, TValue>.Keys.ToArray().
the following c# example code demonstrate us how can we convert dictionary keys to an array programmatically at run time in an application.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Program { static void Main(string[] args) { Dictionary<string, string> colors = new Dictionary<string, string>(); colors.Add("Fuchsia", "#FF00FF"); colors.Add("GoldenRod", "#DAA520"); colors.Add("Lavender", "#E6E6FA"); colors.Add("LightGreen", "#90EE90"); Console.WriteLine("Dictionary Keys | Values....."); foreach (KeyValuePair<string, string> pair in colors) { Console.WriteLine("Key= " + pair.Key + " | Value= " + pair.Value); } string[] colorKeyArray = colors.Keys.ToArray(); Console.WriteLine("\nColor Array Items...."); foreach (string color in colorKeyArray) { Console.WriteLine(color); } Console.ReadLine(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Dictionary Keys | Values..... Key= Fuchsia | Value= #FF00FF Key= GoldenRod | Value= #DAA520 Key= Lavender | Value= #E6E6FA Key= LightGreen | Value= #90EE90 Color Array Items.... Fuchsia GoldenRod Lavender LightGreen |