Alex Rivera | Logout

How do I get previous key from SortedDictionary?

Asked 2011-01-18T05:09:44.657
21

I have dictionary containing key value pairs.

SortedDictionary<int,int> dictionary=new SortedDictionary<int,int>();
dictionary.Add(1,33);
dictionary.Add(2,20);
dictionary.Add(4,35);

I want to get previous key value pair from a known key value. In the above case, if I have key 4, then how can I get <2,20>?

Edit
Report

2 Answers

1

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

public int GetPreviousKey(int currentKey, SortedDictionary<int, int> dictionary)
{
    int previousKey = int.MinValue;
    foreach(KeyValuePair<int,int> 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.

answered 2011-01-18T05:17:59.780
0

How about this? I havent tested it though, but should give something to start think in this direction. Hope it helps.

        int input = 4;
        List<int> lKeys = dictionary.Keys.ToList();
        int reqIndex = lKeys.IndexOf(input) - 1;
        int reqAnswer = dictionary[reqIndex];

test for other conditions like if (reqIndex != -1) etc..

answered 2011-01-18T05:42:39.440

Your Answer