How to get all the keys (only keys) from dictionary object without going through for each loop

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


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();

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.


string[] myKeys;
myKeys = myDictionary.Keys.ToArray();

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


You can use:-

dict.Select(p => $"Keys in dict: {p.Key}")