Next key in C# Dictionary
Solution 1
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()
?
Solution 2
Maybe this is useful to somebody:
public Dictionary<string, int> myDictionary = new Dictionary<string, int>();
public string myCurrentKey = "some key 5";
for (int i = 1; i <= 10; i++) {
myDictionary.Add(string.Format("some key {0}", i), i);
}
private void MoveIndex(int dir) { // param "dir" can be 1 or -1 to move index forward or backward
List<string> keys = new List<string>(myDictionary.Keys);
int newIndex = keys.IndexOf(myCurrentKey) - dir;
if (newIndex < 0) {
newIndex = myDictionary.Count - 1;
} else if (newIndex > myDictionary.Count - 1) {
newIndex = 0;
}
myCurrentKey = keys[newIndex];
}
Debug.Log(string.Format("Current value: {0}", myDictionary[myCurrentKey])); // prints 5
MoveIndex(1);
Debug.Log(string.Format("Current value: {0}", myDictionary[myCurrentKey])); // prints 6
MoveIndex(-1);
MoveIndex(-1);
Debug.Log(string.Format("Current value: {0}", myDictionary[myCurrentKey])); // prints 4
Solution 3
If you have Framework >=3.5 installed use SkipWhile Janus Tondering and LukeH suggested. For lower framework versions you have to do it for yourself(f.e. fill a second dictionary with the keyvaluepairs from your key to the end).
Solution 4
You can't do that with Dictionary. You can accomplish that having possibility of accessing by index, so you can use SortedList instead of Dictionary. Also you can have a look at SkipWhile.
Although you can have some workaround like this :
Dictionary<int, int> dictionary = new Dictionary<int, int>();
foreach (KeyValuePair<int, int> pair in dictionary)
{
// you can check the key you need and assume that the next one will be what you need.
}
But of course this is not the best idea.
Related videos on Youtube
![Betamoo](https://i.stack.imgur.com/tNrKk.jpg?s=256&g=1)
Betamoo
I love Algorithms, Programming, AI and machine learning In my spare time, I like playing real time strategy games, chess, watching movies.
Updated on April 29, 2022Comments
-
Betamoo about 2 years
How to get an
Enumerator
to an item in a -Sorted- dictionary using key?Note:
GetEnumerator()
gets anEnumerator
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 usingMoveNext()
for example...Edit: Or a way to access next elements...
Edit: I prefer a const time method...
Thanks
-
vapcguy almost 8 yearsHow would this method be used/called?