Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# PriorityQueue
Next article icon

C# PriorityQueue

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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:

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:

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:

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:

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:

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:

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.


Next Article
C# PriorityQueue

M

musklf2s
Improve
Article Tags :
  • C#
  • CSharp-PriorityQueue

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences