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?
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.
Dictionary<string, object> dict = new Dictionary<string, object>(); var arr = dict. Select(z => z. Value). ToArray();
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With