49

I checking to see if we have any way to return all the keys to array without using the for each loop (there is no constraint for me to use for each loop i am just looking is there any other way)

Thanks in advance

Grasshopper
  • 1,778
  • 6
  • 27
  • 48
  • 2
    see related [how-to-get-the-list-of-key-in-dictionary-c-sharp](http://stackoverflow.com/questions/1276763/how-to-get-the-list-of-key-in-dictionary-c-sharp?rq=1) – nawfal Mar 30 '13 at 20:32
  • Possible duplicate of [How do I get the list of keys in a dictionary?](https://stackoverflow.com/questions/1276763/how-do-i-get-the-list-of-keys-in-a-dictionary) – Malcolm Sep 11 '19 at 22:07

4 Answers4

90

I'm not certain from your wording whether you want the keys or the values. Either way, it's pretty straightforward. Use either the Keys or Values property of the dictionary and the ToArray extension method.

var arrayOfAllKeys = yourDictionary.Keys.ToArray();

var arrayOfAllValues = yourDictionary.Values.ToArray();
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • hm... It doesn't work for me - System.Collections.Generic.Dictionary.KeyCollection' does not contain a definition for 'ToArray' and no extension method 'ToArray' accepting a first argument of type 'System.Collections.Generic.Dictionary.KeyCollection' could be found (are you missing a using directive or an assembly reference?) – Andrii Muzychuk Aug 12 '15 at 21:08
  • 6
    @Chiz: `ToArray` is a LINQ extension method so you'll need a `using System.Linq;` directive at the top of your code. – LukeH Aug 12 '15 at 22:23
5

You want the keys or the values?

The keys you can get like this:

dictionary.Keys.ToArray();

The values you can get like this;

dictionary.Values.ToArray();

This ToArray method is from System.Linq.Enumerable.

Tiago Ribeiro
  • 217
  • 1
  • 3
3
string[] myKeys;
myKeys = myDictionary.Keys.ToArray();

Untested, but I don't see why it would work.

Ryan O'Neill
  • 1,710
  • 2
  • 13
  • 24
  • This code: `var arrayOfAllKeys = yourDictionary.Keys.ToArray();` Posted by LukeH is better , because this code less and more understandable. and accessible value via under code : `arrayOfAllKeys.[0].ToString();` thanks. – Amin Ghaderi Sep 23 '13 at 07:09
1

You can use:-

dict.Select(p => $"Keys in dict: {p.Key}")
ugola
  • 300
  • 3
  • 18