typestar

PriorityQueue in C#

The heap that serves the most urgent item first.

// a PriorityQueue serves the smallest priority first
var triage = new PriorityQueue<string, int>();
triage.Enqueue("reboot the router", 3);
triage.Enqueue("datacenter on fire", 1);
triage.Enqueue("update the wiki", 9);
triage.Enqueue("rotate the leaked key", 1);

while (triage.TryDequeue(out var task, out var priority))
{
    Console.WriteLine($"p{priority}: {task}");
}

How it works

  1. Enqueue(item, priority) files work under a rank.
  2. TryDequeue hands back element and priority together.
  3. Equal priorities are both rank 1 here; ties have no fixed order.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
369
Tokens
74
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 2 of 3 in More collections, step 11 of 17 in The .NET library.

← Previous Next →