user34537
user34537

Reputation:

Find index of a key? Dictionary .NET

I need to do currentKey+1. So i would like to find the index of the key value and get the next key (or first if at end). How do i find the current index of the key?

I am using a Dictionary<int, classname> and i looked for .Find or IndexOf with Linq to no avail.

Upvotes: 2

Views: 12837

Answers (3)

Omni Chris
Omni Chris

Reputation: 21

Without using a different collection it could be done like this. Though I'm not sure how efficient this is.

classIndex = classes.ToList().IndexOf(new KeyValuePair<int, classname>(newKey, classes[newKey]));

Upvotes: 2

Michael Stum
Michael Stum

Reputation: 181104

Dictionaries are not sorted, so the Key doesn't have any index really. See my question here: Accessing a Dictionary.Keys Key through a numeric index

Use an OrderedDictionary which has an indexer that takes an Int.

Edit: 'm not really sure I understand what you want. If you want to iterate through a Dictionary, just use

foreach(KeyValuePair kvp in yourDict)

If the key is an Int and you want the next, use

var newkey = oldkey+1;
if(yourdict.ContainsKey(newkey)){
    var newvalue = yourdict[newkey];
}

If the ints are not sequential, you can use

var upperBound = d.Max(kvp => kvp.Key)+1; // to prevent infinite loops
while(!yourdict.ContainsKey(newkey) && newkey < upperBound) {
    newkey++;
}

or, alternatively:

var keys = (from key in yourdict.Keys orderby key select key).ToList();
// keys is now a list of all keys in ascending order

Upvotes: 6

Dean Harding
Dean Harding

Reputation: 72678

As Michael Stum noted, Dictionary<TKey, TValue> is not sorted (it's a hashtable) so there is no such thing as the "index" of a key. Instead, you can use SortedList which is (as the name implies) sorted and does provide an IndexOfKey method.

Be aware that the performance characteristics of Dictionary<TKey, TValue> is different to SortedList<TKey, TValue> though. While Dictionary is O(1) for inserts and deletes, SortedList is O(logn).

Upvotes: 2

Related Questions