Search code examples
c#dictionarypriority-queuesorteddictionary

Dequeue in a Priority queue using a Sorted Dictionary in C#


I have a sorted dictionary of the form:

SortedDictionary<PriorityType, List<T>> dictionary;

where PriorityType is an enum class.

Now I am trying to make Priority queue methods but I have apprehensions about whether my Dequeue method will work or not.

public T Dequeue()
    {
        if (IsEmpty())
        {
            throw new Exception("The Priority Queue is empty! Dequeuing is not possible!");
        }

        var highestPriorityList = dictionary[dictionary.Keys.First()];
        var topElement = highestPriorityList.FirstOrDefault();
        if (highestPriorityList.Count == 0)
        {
            dictionary.Remove(dictionary.Keys.First());
        }
        highestPriorityList.RemoveAt(0);
        return topElement;
    }

Please help me to improve this method!

Note: The Dequeue() method is supposed to Remove and return the object with the highest priority and which is before other elements with same priority.


Solution

  • Okay so I was able to modify the above code to suit my dequeue operation!

    public T Dequeue()
        {
            var highestPriorityList = dictionary[dictionary.Keys.First()];
            if (highestPriorityList.Count == 0)
            {
                dictionary.Remove(dictionary.Keys.First());
            }
            var topElement = highestPriorityList.First();
            highestPriorityList.Remove(topElement);
            return topElement;
        }
    

    Now I can dequeue for as long as I like without the InvalidOperationException which was caused by the missing element in the list after the RemoveAt operation!