Convert Dictionary.keyscollection to array of strings

C#Collections

C# Problem Overview


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 an array of Strings?

C# Solutions


Solution 1 - C#

Assuming you're 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);

Solution 2 - C#

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

string[] keys = dictionary.Keys.Select(x => x.ToString()).ToArray();

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

Or perhaps a handy generic extension...

    public static T2[] ToValueArray<T1, T2>(this Dictionary<T1, T2> value)
    {
        var values = new T2[value.Values.Count];
        value.Values.CopyTo(values, 0);

        return values;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#Thomas LevesqueView Answer on Stackoverflow
Solution 2 - C#Kim JohanssonView Answer on Stackoverflow
Solution 3 - C#FoxfireView Answer on Stackoverflow
Solution 4 - C#LJMView Answer on Stackoverflow
Solution 5 - C#Craig GView Answer on Stackoverflow