Search code examples
c#dictionaryenumscomparable

SortedDictionary ContainsKey method wrong?


So basically I have something like this:

private SortedDictionary<Priority, List<String>> example = new SortedDictionary<Priority, List<String>>(new PriorityComparer());

public void Submit(Priority priority, String test)
{
    if (!example.ContainsKey(priority))
    {
        example.Add(priority, new List<String> { test });
        // adds an entry with the key (Priority.Low) twice, why?
    }
    else
    {
        example[priority].Add(test); // never called
    }
}

For just submitting a bunch of test elements:

Submit(Priority.Critical, "test4");
Submit(Priority.Low, "test");
Submit(Priority.Normal, "test3");
Submit(Priority.Low, "test2");

Priority is just an enum with priority levels ranging anywhere from Low (0) to Critical (10). It's just a typical enum, nothing fancy.

Priority comparer:

public class PriorityComparer : IComparer<Priority>
{
    public int Compare(Priority x, Priority y)
    {
        if (x > y)
        {
            return -1;
        }
        else
        {
            return 1;
        }
    }
}

Solution

  • Your compare implementation is incomplete. You're missing the case when x == y (return 0).