New Generic Collection In .NET 6 - A Priority Queue

Introduction

In this article, we are going to learn about a new data structure introduced in .NET 6, a Priority Queue. The usage of priority queue is to allow us to add elements with a priority number which will be used to dequeue based on priority number. Unlike a normal queue that uses the concept of first-in-first-out, it works based on the priority of a value assigned to a value. There are many use cases when priority is a primary requirement.

Here are a few,

  1. Think of a membership type, a gold membership should have first priority. Silver should be second and so on.
  2. Priority in terms of facilities, medical treatment, etc. Think of the age group, a person with more age must be given first priority. Less age, less priority.
  3. A vehicle repair service center. Based on business requirements, maybe a more damaged vehicle requires more attention because it will generate more value.

We can think of several use cases. Please add those in the comments as well so that we can share them with everyone.

How does it work?

It is available as part of the namespace “System.Collections.Generic” as it is part of the generic collection. The class name is “PriorityQueue”. Generic Type is “PriorityQueue<TElement, TPriority>”.

A few common methods are available,

void Enqueue(TElement element, TPriority priority);

To Add Element Based on Priority

  1. TElement Peek();
  2. TElement TryPeek(out TElement element, out TPriority priority);

To Get elements without removing them from the queue.

  1. TElement Dequeue();
  2. TElement TryDequeue(out TElement element, out TPriority priority);

To get elements from the queue based on priority. Lower the priority first out from the queue. For the same priority, the order is not guaranteed.

TElement EnqueueDequeue(TElement element, TPriority priority);

Will get the element based on priority and add elements at the same time.

void EnqueueRange(IEnumerable<(TElement Element, TPriority Priority)> values);

Inserts a lot of elements at once. We should use the Tuple type to insert.

void EnqueueRange(IEnumerable<TElement> values, TPriority priority);

Inserts a lot of elements at once. All with the same priority.

Code Walkthrough

Here we are going to build a vehicle service queue. This will include covering various services from general service to repair in the vehicle repair queue every time we pass priority with the value of car severity.

Note
When priority is the same then output order is not guaranteed.

using System;
using System.Collections.Generic;
namespace TutorialApp.ConsoleApp {
    class Program {
        static void Main(string[] args) {
            PriorityQueue < string, int > vehicleRepairQueue = new PriorityQueue < string, int > ();
            vehicleRepairQueue.Enqueue("Mirror Damaged Car", 3);
            vehicleRepairQueue.Enqueue("Wash Car", 10);
            vehicleRepairQueue.Enqueue("Severe Damaged Car", 1);
            System.Console.WriteLine("\nVehicle Repair Queue:\n");
            while (vehicleRepairQueue.Count > 0) {
                System.Console.WriteLine(vehicleRepairQueue.Dequeue());
            }
            /*
            Output: 
            Severe Damaged Car
            Mirror Damaged Car
            Wash Car
            */
            System.Console.WriteLine("\nVehicle Service Queue:\n");
            vehicleRepairQueue.Enqueue("General Service Sedan Car", 5);
            var lastDequeue = vehicleRepairQueue.EnqueueDequeue("General Service Suv Car", 7);
            System.Console.WriteLine(lastDequeue); // Output: General Service Sedan Car
            var severeDamagedVehicles = new List < string > {
                "Car Damaged Sedan",
                "Car Damaged SUV",
                "Car Damaged Hatchback"
            };
            vehicleRepairQueue.EnqueueRange(severeDamagedVehicles, 1);
            System.Console.WriteLine("\nVehicle Bulk Damage Queue:\n");
            while (vehicleRepairQueue.Count > 0) {
                System.Console.WriteLine(vehicleRepairQueue.Dequeue());
            }
            /*
            Output:
            Car Damaged Sedan        
            Car Damaged Hatchback    
            Car Damaged SUV
            General Service Suv Car 
            */
            System.Console.WriteLine("\nBulk Service Queue:\n");
            var bulkServiceVehiclesRequest = new List < (string, int) > {
                ("Tyre Change Request 1", 3),
                ("Tyre Change Request 2", 3),
                ("Tyre Change Request 3", 3),
                ("Tyre Change Request 4", 3),
                ("Severe Damaged Car", 1)
            };
            vehicleRepairQueue.EnqueueRange(bulkServiceVehiclesRequest);
            while (vehicleRepairQueue.Count > 0) {
                System.Console.WriteLine(vehicleRepairQueue.Dequeue());
            }
            /*
            Output:
            Severe Damaged Car
            Tyre Change Request 1
            Tyre Change Request 4
            Tyre Change Request 3
            Tyre Change Request 2
            */
        }
    }
}

 Combined Output

New Generic Collection in .NET 6 a Priority Queue

Summary

We got a glimpse of how the priority queue works. We covered the following things,

  1. Introduction and Use cases
  2. Common Methods
  3. Implementation code walkthrough using a vehicle repair service queue.

I hope this will be useful in the implementation of various use cases in your next project. Thanks for reading !!!


Recommended Free Ebook
Similar Articles