Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 718
Grasshopper Avatar asked Mar 03 '11 23:03

Grasshopper


People also ask

Can a dictionary object be a key?

00:19 A key must be immutable—that is, unable to be changed. These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key.

Can dictionary have only keys Python?

Given a List, the task is to create a dictionary with only keys by using given list as keys.


4 Answers

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();
like image 172
LukeH Avatar answered Oct 01 '22 02:10

LukeH


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.

like image 29
Tiago Ribeiro Avatar answered Oct 01 '22 02:10

Tiago Ribeiro


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

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

like image 26
Ryan O'Neill Avatar answered Oct 01 '22 02:10

Ryan O'Neill


You can use:-

dict.Select(p => $"Keys in dict: {p.Key}")
like image 38
Urvika G Avatar answered Oct 01 '22 01:10

Urvika G