Accessing a Dictionary.Keys Key through a numeric index

Michael Stum picture Michael Stum · Aug 7, 2008 · Viewed 267.2k times · Source

I'm using a Dictionary<string, int> where the int is a count of the key.

Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:

int LastCount = mydict[mydict.keys[mydict.keys.Count]];

does not work, because Dictionary.Keys does not implement a []-indexer.

I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?

Answer

Vitor Hugo picture Vitor Hugo · Jan 19, 2011

As @Falanwe points out in a comment, doing something like this is incorrect:

int LastCount = mydict.Keys.ElementAt(mydict.Count -1);

You should not depend on the order of keys in a Dictionary. If you need ordering, you should use an OrderedDictionary, as suggested in this answer. The other answers on this page are interesting as well.