Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Dictionary.keyscollection to array of strings

Tags:

c#

collections

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?

like image 656
leora Avatar asked Oct 25 '09 16:10

leora


People also ask

How do you convert a dictionary value to an array?

To convert a dictionary to an array in Python, use the numpy. array() method, and pass the dictionary object to the np. array() method as an argument and it returns the array.

How to convert a dictionary key and value to an array c#?

Dictionary<string, object> dict = new Dictionary<string, object>(); var arr = dict. Select(z => z. Value). ToArray();

Can a dictionary key be an array?

A dictionary is sometimes called an associative array because it associates a key with an item. The keys behave in a way similar to indices in an array, except that array indices are numeric and keys are arbitrary strings. Each key in a single Dictionary object must be unique.


2 Answers

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); 
like image 71
Thomas Levesque Avatar answered Sep 21 '22 06:09

Thomas Levesque


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.

like image 31
Foxfire Avatar answered Sep 23 '22 06:09

Foxfire