With the arrival of .NET 6, we have a new collection type, the PriorityQueue
(priority queues). In this post, we’ll see how to work with it.
Index
1 - What is PriorityQueue in C#?
Previously, we saw the Queue<T>
type, which represents a FIFO queue.
The PriorityQueue
type allows us to specify the position in which we want to insert each element we want to add. This new type is represented as PriorityQueue<TElement, TPriority>()
; the first generic type will contain our value, and the second one defines the priority.
Using PriorityQueue
can feel quite similar to using a SortedList, but they are not the same, because queues aren’t intended to be used as lists , even though it’s technically possible.
2 - Creating a PriorityQueue and adding elements in C#
To create a priority queue (PriorityQueue
), we just need to instantiate it and call the .Enqueue()
method to insert elements. Remember, we must pass two parameters: the value and the priority.
PriorityQueue<string, int> colaPrioridad = new PriorityQueue<string, int>();
colaPrioridad.Enqueue("Opel", 2);
colaPrioridad.Enqueue("Audi", 1);
colaPrioridad.Enqueue("BMW", 3);
- Note: if you add multiple elements with the same priority, they’ll be dequeued in reverse order
3 - Receiving elements from a PriorityQueue in C#
To retrieve elements, we have three options
Peek()
: This returns the next item in the queue without removing it.Dequeue()
: This returns the next item and also removes it from the queue.EnqueueDequeue()
: Alternatively, you can use this, which lets you both retrieve an item from the queue and insert a new one at the same time.
string resultPeek = colaPrioridad.Peek();
string resultDequeue = colaPrioridad.Dequeue();
string resultDequeue2 = colaPrioridad.EnqueueDequeue("Mazda", 3);
Console.WriteLine(resultPeek); //Audi
Console.WriteLine(resultDequeue); //Audi again
Console.WriteLine(resultDequeue2); //Opel
4 - Removing elements from a priority queue in C#
To remove elements from a priority queue without retrieving them, the only option is to clear the queue using .Clear()
.
colaPrioridad.Clear();
Conclusion
In this post, we’ve seen how to create a priority queue in C#
How to add elements to a priority queue
How to retrieve elements from a priority queue.
If there is any problem you can add a comment bellow or contact me in the website's contact form