Search code examples
c#dictionarycollectionsicollection

How to get the key of an OrderedDict at a given index?


I'm seemingly unable to find a quick solution for an apparently simple problem: I have a C# OrderedDict, and, utilizing prior knowledge of the order, want to retrieve a key at a certain position.

OrderedDict.Keys returns an ICollection object, but I could not find a straightforward way to retrieve an element at a certain position.

I have solved it for now by building a list in a foreach loop using .Keys and indexing that, but that does not seem to be elegant to me.

Coming from Python, I am basically looking for an list(someOrderedDict.keys())[index] equivalent. Is there something like that in C#?


Solution

  • If it's OrderedDictionary you mean there is no elegant way bar writing your own class. The most elegant way (perhaps not efficient) using OrderedDictionary is potentially:

    var key = orderedDictionary.Keys.OfType<object>().Skip(index).First();