Convert Dictionary.keyscollection to string array

I have a Dictionary<string, List<Order>> , and I want to have a list of keys in an array. But when I choose

 string[] keys = dictionary.Keys; 

This does not compile.

How to convert KeysCollection to an array of strings?

+43
collections c #
25 Oct '09 at 16:41
source share
4 answers

Assuming you are using .NET 3.5 or later ( using System.Linq; ):

 string[] keys = dictionary.Keys.ToArray(); 

Otherwise, you will have to use the CopyTo method or use a loop:

 string[] keys = new string[dictionary.Keys.Count]; dictionary.Keys.CopyTo(keys, 0); 
+83
Oct 25 '09 at 16:43
source share

With dictionary.Keys.CopyTo (keys, 0);

If you don't need an array (which you usually don't need), you can just iterate over the keys.

+4
Oct 25 '09 at 16:49
source share

Use this if your keys do not have a string type. This requires LINQ.

 string[] keys = dictionary.Keys.Select(x => x.ToString()).ToArray(); 
+2
Oct 25 '09 at 16:47
source share

Unfortunately, I don't have VS nearby to check this out, but I think something like this might work:

 var keysCol = dictionary.Keys; var keysList = new List<???>(keysCol); string[] keys = keysList.ToArray(); 

Where??? this is your key type.

0
Oct. 25 '09 at 16:45
source share



All Articles