How do I get previous key from SortedDictionary?

后端 未结 7 2247
误落风尘
误落风尘 2020-12-18 20:46

I have dictionary containing key value pairs.

SortedDictionary dictionary=new SortedDictionary();
dictionary.Add(1,33);
diction         


        
7条回答
  •  长情又很酷
    2020-12-18 20:53

    You could loop through the dictionary and keep track of values, I guess. Something like this:

    public int GetPreviousKey(int currentKey, SortedDictionary dictionary)
    {
        int previousKey = int.MinValue;
        foreach(KeyValuePair pair in dictionary)
        {
            if(pair.Key == currentKey)
            {
                if(previousKey == int.MinValue)
                {
                    throw new InvalidOperationException("There is no previous key.");
                }
                return previousKey;
            }
            else
            {
                previousKey = pair.Key;
            }
        }
    }
    

    However, this is a pretty odd operation to require. The fact that you need it might be pointing at a problem with your design.

提交回复
热议问题