tags:

views:

491

answers:

4

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

string[] keys = dictionary.Keys;

this doesn't compile.

how do i convert KeysCollection to array of strings.

+7  A: 

Assuming you're using .NET 3.5 or later :

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);
Thomas Levesque
A: 

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

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

where ??? is your key type.

L. Moser
A: 

Use this if your keys isn't of type string. It requires LINQ.

string[] keys = dictionary.Keys.Select(x => x.ToString()).ToArray();
Kim Johansson
This returns an `IEnumerable<string>`, not a `string[]`
Thomas Levesque
Also, it's clear from the OP that the keys are of type `string` (though originally there was a formatting problem that prevented it from showing).
280Z28
As my answer says, use it if your key isn't of type string and you still want a string...
Kim Johansson
+3  A: 

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

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

Foxfire
+1 for "... iterate over the Keys"; that generally seems better than copying them out.
Dan