priority queue
.NET
C#
data structures
programming

Priority queue in .Net

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

A priority queue is a data structure where the next removed item is chosen by priority rather than simple insertion order. In modern .NET, the easiest built-in solution is PriorityQueue<TElement, TPriority>, which was added in .NET 6.

If you are on an older runtime, you usually build your own structure or simulate one with collections such as SortedDictionary. The right choice depends on your .NET version and whether you need a quick utility or a high-throughput implementation.

Use the Built-In PriorityQueue in .NET 6+

For current .NET versions, the standard library already provides a priority queue.

csharp
1using System;
2using System.Collections.Generic;
3
4var pq = new PriorityQueue<string, int>();
5
6pq.Enqueue("low", 5);
7pq.Enqueue("high", 1);
8pq.Enqueue("medium", 3);
9
10while (pq.Count > 0)
11{
12    Console.WriteLine(pq.Dequeue());
13}

This prints items in ascending priority order because lower numeric priority values come out first.

That detail matters: PriorityQueue<TElement, TPriority> is effectively a min-priority queue by default.

Peek Without Removing

You can inspect the next item without removing it.

csharp
1var pq = new PriorityQueue<string, int>();
2pq.Enqueue("critical", 0);
3pq.Enqueue("normal", 10);
4
5Console.WriteLine(pq.Peek());

That is useful when you need to know which item is next but cannot consume it yet.

If You Want Higher Numbers to Mean Higher Priority

Many programmers naturally expect a bigger number to mean a higher priority. With the built-in queue, you can just invert the number or use a custom comparison strategy by transforming the value before enqueueing.

csharp
1var pq = new PriorityQueue<string, int>();
2
3// Higher business priority becomes lower queue priority number.
4pq.Enqueue("urgent", -100);
5pq.Enqueue("normal", -10);
6pq.Enqueue("low", -1);
7
8Console.WriteLine(pq.Dequeue());

The queue API itself is simple, but agreeing on the priority convention in your codebase is important.

Older .NET Versions

If you are not on .NET 6 or later, a common fallback is SortedDictionary<TPriority, Queue<TElement>>.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5var queues = new SortedDictionary<int, Queue<string>>();
6
7void Enqueue(string value, int priority)
8{
9    if (!queues.TryGetValue(priority, out var q))
10    {
11        q = new Queue<string>();
12        queues[priority] = q;
13    }
14    q.Enqueue(value);
15}
16
17string Dequeue()
18{
19    var first = queues.First();
20    var value = first.Value.Dequeue();
21    if (first.Value.Count == 0)
22        queues.Remove(first.Key);
23    return value;
24}

This is more verbose and usually less efficient than a binary-heap-based implementation, but it is often good enough for modest workloads.

Typical Use Cases

Priority queues show up in:

  • Dijkstra and A* pathfinding
  • task scheduling
  • event simulation
  • rate-limited work queues
  • load-shedding or retry systems

So even when the question sounds academic, the data structure appears in many real systems.

A Note on Stability

A priority queue does not automatically promise stable ordering for items with equal priority unless the implementation explicitly does that. If equal-priority order matters, add a sequence number to the priority key or wrap the priority value in a composite rule.

That is a subtle requirement many developers discover only when tests start failing intermittently.

Common Pitfalls

  • Assuming .NET had a built-in priority queue long before .NET 6.
  • Forgetting that the built-in PriorityQueue dequeues the lowest priority value first.
  • Expecting stable ordering for equal priorities without designing for it.
  • Reimplementing a priority queue poorly when the built-in type already exists.
  • Using a priority queue when a normal FIFO queue would have been simpler and clearer.

Summary

  • In .NET 6 and later, use PriorityQueue<TElement, TPriority>.
  • The built-in queue is min-priority by default, so lower numbers come out first.
  • On older runtimes, SortedDictionary or a custom heap can fill the gap.
  • Be explicit about how you interpret priority values.
  • If equal-priority ordering matters, design for stability instead of assuming it.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.