In C#, the PriorityQueue class is present in the System.Collections.Generic namespace. It stores elements according to their priority. Elements with greater priority are removed from the queue before those with lesser priority. It can be implemented using SortedList or SortedDictionary.
- Elements are inserted with an associated priority.
- Elements are removed based on their priority, lower numerical priority values are dequeued first (since PriorityQueue in C# is a min-heap).
- The queue ensures that the elements with the lowest priority value are dequeued first.
- Elements are sorted internally according to their priority values.
Example: This example demonstrates how to add elements with priorities to a PriorityQueue and then dequeue and display them in order of their priority (lowest first).
C# // C# program to demonstrates // the working of PriorityQueue using System; using System.Collections.Generic; class Geeks { static void Main() { // Create a priority queue var pq = new PriorityQueue<string, int>(); // Add elements with their priorities pq.Enqueue("Task 1", 10); pq.Enqueue("Task 2", 20); pq.Enqueue("Task 3", 30); Console.WriteLine( "Elements added to the PriorityQueue."); // Dequeue elements and display them while (pq.Count > 0) { pq.TryDequeue(out string task, out int priority); Console.WriteLine($"Dequeued: {task} with priority {priority}"); } } }
Output:
Note: The PriorityQueue<TElement, TPriority> class is available only in .NET 6 and later. Ensure your project targets .NET 6 or higher to avoid compilation errors.
PriorityQueue Hierarchy
The below diagram demonstrates the Priorityqueue Hierarchy:
Declaration of PriorityQueue
In C#, the declaration of PriorityQueue can be done as:
PriorityQueue<TElement, TPriority> pq = new PriorityQueue<TElement, TPriority>();
Note: To declare a priority queue, specify the type for both elements and the priority.
Constructors
Constructor | Description |
---|
PriorityQueue<TElement, TPriority>() | Initializes a new empty priority queue. |
PriorityQueue<TElement, TPriority>(int capacity) | Initializes a priority queue with a specified initial capacity. |
PriorityQueue<TElement, TPriority>(IComparer<TPriority> comparer) | Initializes the queue with a custom priority compare. |
Example: This example demonstrates how to use a PriorityQueue to enqueue tasks with priorities and dequeue them in order of their priority.
C# // C# program to demonstrates priorityQueue using System; class Geeks { static void Main() { // Create a priority queue with default constructor PriorityQueue<string, int> pq = new PriorityQueue<string, int>(); // Enqueue elements with their priorities pq.Enqueue("Task 1", 1); pq.Enqueue("Task 2", 2); pq.Enqueue("Task 3", 3); // Dequeue elements and print them Console.WriteLine("Priority Queue (dequeued elements):"); while (pq.Count > 0) { // Use TryDequeue and capture // the element and its priority // Dequeues and returns the element and its priority pq.TryDequeue(out string element, out int priority); // Access the element and its priority Console.WriteLine($"{element} with priority {priority}"); } } }
Output:
Properties
Properties | Description |
---|
Comparer | Defines how elements are ordered based on their priority (default or custom) |
Count | Returns the number of elements in the PriorityQueue |
UnorderedItems | Provides an unordered collection of elements in the PriorityQueue for iteration. Iteration does not guarantee order since it does not sort elements. |
Performing Various Operations on PriorityQueue
1. Adding Elements: We can use Enqueue() method to insert elements to the priority queue with a specified priority.
Example: This example demonstrates how to add elements with priorities to a PriorityQueue then dequeue and display them in order of their priority.
C# // Add elements in PriorityQueue using System; using System.Collections.Generic; class Geeks { static void Main() { // Create a priority queue var pq = new PriorityQueue<string, int>(); // Add elements with their priorities pq.Enqueue("Task 1", 1); pq.Enqueue("Task 2", 2); pq.Enqueue("Task 3", 3); Console.WriteLine("Elements added to the PriorityQueue."); // Dequeue elements and display them while (pq.Count > 0) { pq.TryDequeue(out string task, out int priority); Console.WriteLine($"Dequeued: {task} with priority {priority}"); } } }
Output:
2. Removing Elements: We can use methods like Dequeue() and TryDequeue() methods to remove elements from the priority queue.
Example: This example demonstrates how to safely remove the highest-priority element from a priority queue using TryDequeue().
C# // Remove elements from PriorityQueue using System; using System.Collections.Generic; class Geeks { static void Main() { // Create a priority queue PriorityQueue<string, int> pq = new PriorityQueue<string, int>(); // Add elements to the queue pq.Enqueue("Task 1", 1); pq.Enqueue("Task 2", 2); pq.Enqueue("Task 3", 3); // Remove and print the highest priority element if (pq.TryDequeue(out string task, out int priority)) { Console.WriteLine($"Removed: {task} with priority {priority}"); } } }
Output:
3. Accessing Element: We can use TryPeek() method to access the element with highest priority.
Example: This example demonstrates how to access the highest-priority element in a priority queue without removing it using the TryPeek() method.
C# // Accessing element in PriorityQueue using System; using System.Collections.Generic; class Geeks { static void Main() { // Create a priority queue PriorityQueue<string, int> pq = new PriorityQueue<string, int>(); // Add elements to the queue pq.Enqueue("Task 1", 1); pq.Enqueue("Task 2", 2); pq.Enqueue("Task 3", 3); // Access the highest priority // element without removing it pq.TryPeek(out string task, out int priority); Console.WriteLine($"Peeked: {task} with priority {priority}"); } }
Output:
4. Iterating Elements: We can use the unorderedItems property to iterate over the elements of priority queue.
Example: This example demonstrates how to iterate over all elements in a PriorityQueue using the UnorderedItems property without altering the queue.
C# // Iterating over the PriorityQueue using System; using System.Collections.Generic; class Geeks { static void Main() { // Create a priority queue PriorityQueue<string, int> pq = new PriorityQueue<string, int>(); // Add elements to the queue pq.Enqueue("Task 1", 1); pq.Enqueue("Task 2", 2); pq.Enqueue("Task 3", 3); // Iterate over the elements using UnorderedItems Console.WriteLine("Iterating over elements in the PriorityQueue:"); foreach (var item in pq.UnorderedItems) { Console.WriteLine($"{item.Element} with priority {item.Priority}"); } } }
Output:
Methods
Methods | Description |
---|
Clear() | Removes all elements from the PriorityQueue |
Dequeue() | Removes and returns the element with the lowest priority from the queue. |
DequeueEnqueue(TElement, TPriority) | Removes the lowest priority element and adds a new element with specified priority. |
Enqueue(TElement, TPriority) | Adds an element with its priority to the PriorityQueue |
EnqueueDequeue(TElement, TPriority) | Adds an element and removes the lowest priority element, returning the removed one. |
EnqueueRange(IEnumerable<TElement>, TPriority) | Adds a range of elements with the same priority to the PriorityQueue |
EnqueueRange(IEnumerable<ValueTuple<TElement, TPriority>>) | Adds a range of elements with their respective priorities to the PriorityQueue |
EnsureCapacity(Int32) | Makes sure the queue has enough space for the specified number of items. |
Equals(Object) | Compares the current PriorityQueue object with another object for equality. |
GetHashCode() | Returns a hash code for the PriorityQueue |
GetType() | Returns the type of the current PriorityQueue Object |
MemberwiseClone() | Creates a shallow copy of the current PriorityQueue Object |
Peek() | Returns the element with the lowest priority without removing it from the queue. |
Remove(TElement, TPriority, IEqualityComparer<TElement>) | Removes the first occurrence of the specified element from the queue. |
ToString() | Returns a string representation of the PriorityQueue |
TrimExcess() | Reduces the capacity of the queue to match the current number of elements, optimizing memory usage. |
TryDequeue(TElement, TPriority) | Tries to remove and return the lowest priority element and its priority from the queue. |
TryPeek(TElement, TPriority) | Tries to get the lowest priority element without removing it and returns a boolean indicating success or failure. |
Similar Reads
C# Queue with Examples A Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues.Key Features:FIF
6 min read
C# Thread Priority in Multithreading In a multithreaded environment, each thread has a priority that determines how frequently the thread is allocated CPU resources by the operating system. The Thread.Priority property in C# is used to set or get the priority of a thread.A programmer can explicitly assign a priority to a thread using t
3 min read
C# | Add an object to the end of the Queue - Enqueue Operation Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue. Queue<T>.Enqueue(T) Method is used to add an object to the end
3 min read
C# | Get the object at the beginning of the Queue - Peek Operation Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Queue.Peek Method is used to get the object at the beginning of the Qu
3 min read
PriorityQueue in Java The PriorityQueue class in Java is part of the java.util package. It implements a priority heap-based queue that processes elements based on their priority rather than the FIFO (First-In-First-Out) concept of a Queue.Key Points:The PriorityQueue is based on the Priority Heap. The elements of the pri
9 min read