Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to extract a list of keys from a .NET Dictionary

Tags:

Suspect my brain isn't working today - I need to extract a list of keys, etc:

Dictionary<string, MyClass>  myDict; List<String> myKeys = myDict.Keys; 

The second line fails to compile as the Keys property returns a "KeyCollection" class and not a list<> of key objects.

like image 946
winwaed Avatar asked Mar 08 '11 16:03

winwaed


People also ask

How do you get a list of all the keys in a dictionary?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.

Can list be used as keys of a dictionary C#?

We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .

How get fetch from dictionary in C#?

Get Dictionary Value by Key With [] Method in C# We can get the value in the dictionary by using the key with the [] method in C#. We created a dictionary, mydictionary , with the Dictionary<string, string> class. After that, we retrieved the value of the Key 3 key in mydictionary with the [] method.

How do I access a dictionary in C#?

The Dictionary can be accessed using indexer. Specify a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from the specified index.


1 Answers

Using LINQ you can do the following...

List<String> myKeys = myDict.Keys.ToList(); 

However depending on what your goal is with the keys (selective enumeration etc) it might make more sense to work with the key collection and not convert to a list.

like image 70
Quintin Robinson Avatar answered Oct 21 '22 22:10

Quintin Robinson