Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of a key? Dictionary .NET

Tags:

.net

linq

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.


2 Answers

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
like image 123
Michael Stum Avatar answered Jan 28 '26 01:01

Michael Stum


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

like image 30
Dean Harding Avatar answered Jan 28 '26 01:01

Dean Harding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!