How do I get the key and value of item from OrderedDictionary by index?
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index);
There is not a direct built-in way to do this. This is because for an OrderedDictionary
the index is the key; if you want the actual key then you need to track it yourself. Probably the most straightforward way is to copy the keys to an indexable collection:
// dict is OrderedDictionary object[] keys = new object[dict.Keys.Count]; dict.Keys.CopyTo(keys, 0); for(int i = 0; i < dict.Keys.Count; i++) { Console.WriteLine( "Index = {0}, Key = {1}, Value = {2}", i, keys[i], dict[i] ); }
You could encapsulate this behavior into a new class that wraps access to the OrderedDictionary
.
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