views:

506

answers:

1

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

+1  A: 

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.

Jason
I did same but see once:OrderedDictionary list = OrderItems; object strKey = list[e.OldIndex]; DictionaryEntry dicEntry = new DictionaryEntry(); foreach (DictionaryEntry DE in list) { if (DE.Value == strKey) { dicEntry.Key = DE.Key; dicEntry.Value = DE.Value; } }
Lalit