tags:

views:

76

answers:

2

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.

+5  A: 

Dictionaries are not sorted, so the Key doesn't have any index really. See my question here: http://stackoverflow.com/questions/4227/

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
Michael Stum
Or an OrderedDictionary: http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary_members.aspx
mwilson
@mwilson Very true, I've changed my answer. `Queue<Tuple<TKey,TValue>>` sounded really stupid anyway :)
Michael Stum
hmm, in my function each time i call it should i copy the keys into a list, sort it then use prev/next with that? (i'd still find the current index by scanning the value)
acidzombie24
I dont need order they been added, i need order of key value
acidzombie24
Accepted for the `var keys = (from key in yourdict.Keys orderby key select key).ToList();` answer. My favourable solution. I got it wrong when i tried to write it without reading yours (carefully). I wrote orderby yourdict.Keys[keys] by mistake. Yikes (and ouch, threw an exception which is good but i was confused)
acidzombie24
+2  A: 

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).

Dean Harding