Jul 26, 2012

[How to] Convert Dictionary.Keys (or Values) to Array

For example, there's a dictionary like this,


using System.Collections.Generic;


Dictionary<string, int> dict = new Dictionary<string, int>();


Now we want to retrieve all keys,


var keys = dict.Keys;


That is. However, the keys is another collection type an we want to convert it to array.
There was an old way -- CopyTo.


string[] keyArray = new string[dict.Count];
dict.Keys.CopyTo(keyArray, 0);


If you have looking for better solution, and you're using C# 3.0 (and above).
Congratulation! According the MSDN library, there's a directly way -- ToArray