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.
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.
We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .
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.
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.
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.
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