Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a key from a OrderedDictionary in C# by index?

Tags:

How do I get the key and value of item from OrderedDictionary by index?

like image 843
Red Swan Avatar asked Feb 09 '10 14:02

Red Swan


2 Answers

orderedDictionary.Cast<DictionaryEntry>().ElementAt(index); 
like image 111
Martin R-L Avatar answered Sep 18 '22 17:09

Martin R-L


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.

like image 33
jason Avatar answered Sep 18 '22 17:09

jason