0

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#?

fbmd
  • 730
  • 6
  • 22
  • 1
    the index would be the `key`... Dictionaries are meant to be used with keys. – T McKeown Jun 30 '14 at 15:28
  • 2
    OP wants to retrieve the **key** and not the **value** - maybe `(DictionaryEntry(myDict[index])).Key`? – paul Jun 30 '14 at 15:31
  • As far as I understood, `myDict[index]` retrieves the `Value`, not a `DictionaryEntry`. http://msdn.microsoft.com/en-us/library/ms132598.aspx – fbmd Jun 30 '14 at 15:42
  • You should be able to do `orderedDictionary.Cast().ElementAt(index);` – Icemanind Jun 30 '14 at 19:30
  • `.Cast` needed `System.Linq`. But even then `.Cast()` has no `ElementAt()` method. Am I missing another `using`...`? – fbmd Jul 01 '14 at 08:32

1 Answers1

1

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();
smremde
  • 1,800
  • 1
  • 13
  • 25