Find index of a key? Dictionary .NET

后端 未结 3 1466
不思量自难忘°
不思量自难忘° 2021-01-22 03:10

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

相关标签:
3条回答
  • 2021-01-22 03:23

    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
    
    0 讨论(0)
  • 2021-01-22 03:36

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

    0 讨论(0)
  • 2021-01-22 03:38

    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]));
    
    0 讨论(0)
提交回复
热议问题