Next key in C# Dictionary

Betamoo picture Betamoo · Jul 27, 2010 · Viewed 16.1k times · Source

How to get an Enumerator to an item in a -Sorted- dictionary using key?

Note:GetEnumerator() gets an Enumerator to first element..

But I need to get an Enumerator to the element with a given key in order to gain access to next elements using MoveNext() for example...

Edit: Or a way to access next elements...

Edit: I prefer a const time method...

Thanks

Answer

Janus Tøndering picture Janus Tøndering · Jul 27, 2010
var enumerator = dictionary.Keys.SkipWhile(k => k != myKey)

Where myKey is the key you're looking for. And you can use the OrderBy extension method if you want to have the keys sorted.

Edit: You can't do it in constant with Dictionary/SortedDictionary. Why not implement your own binary search tree (like SortedDictionary is) and you will have O(log n) time lookup and O(1) time .next()?