Let's continue our series on new .NET 6 features with an interesting new way to order objects: PriorityQueue<T, N>
!
Current Implementation
.NET 5 and prior have a class called Queue<T>
, which represents a collection with first-in, first-out (FIFO) behavior. This is roughly the kind of behavior that might happen when people stand in a line; people exit the line in the order they joined it.
When objects are added to the queue (or "enqueued"), they are removed from it (or "dequeued") in the same order as they were added.
Queue<string> names = new Queue<string>();
names.Enqueue("Alex");
names.Enqueue("Leah");
names.Enqueue("Haley");
names.Enqueue("Harvey");
names.Dequeue(); //Alex
names.Dequeue(); //Leah
names.Dequeue(); //Haley
New Implementation
.NET 6 introduces a new class, PriorityQueue<T, N>
, which behaves similarly to a Queue<T>
, except each item in a PriorityQueue<T, N>
also has an order assigned (represented by N
). Items are then dequeued in the order specified by the N
value, not solely by first-in, first-out.
PriorityQueue<string, int> priorityWords = new();
priorityWords.Enqueue("Leah", 2);
priorityWords.Enqueue("Harvey", 4);
priorityWords.Enqueue("Haley", 3);
priorityWords.Enqueue("Alex", 1);
Console.WriteLine(priorityWords.Dequeue()); //Alex
Console.WriteLine(priorityWords.Dequeue()); //Leah
Console.WriteLine(priorityWords.Dequeue()); //Haley
Console.WriteLine(priorityWords.Dequeue()); //Harvey
In a PriorityQueue<T, N>
, the order value can be any primitive type. Assume we have an enumeration called ShowRating
:
public enum ShowRating
{
Transcendant, //1
Amazing, //2
Good, //3
OK //4
}
We could use that enum as the order value in a PriorityQueue<T, N>
to rank a bunch of tv shows.
Demo Project
As with all posts in this series, there is a demo project you can check out over on GitHub that shows these examples of PriorityQueue<T, N>
so you can run them and see the output. Check it out!
Happy Coding!