Topological Sort Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Topological Sort runs in O(V+E) time and O(V) space, in C# as in every other language.
- ✓System.Collections.Generic.Queue<T> is the real, ring-buffer-backed FIFO (O(1) Enqueue/Dequeue), and System.Collections.Generic.PriorityQueue<TElement, TPriority>, added in .NET 6, is the real min-heap for a canonical or deterministic ordering, before .NET 6 there was no priority queue in the BCL at all, and people either hand-rolled a binary heap or reached for a third-party package.
- ✓Queue<T> for the plain version, PriorityQueue<TElement, TPriority> for the canonical-ordering version, never a List<T> re-sorted with .OrderBy() inside the loop, which a reviewer familiar with LINQ's cost model will flag immediately (see pitfall).
- ✓The C# trap: Calling list.OrderBy(...).First() (or re-materializing an ordered list) inside the main loop to pick the next ready node re-sorts the entire remaining collection on every single iteration, turning what should be an O(V log V) priority-queue-based algorithm into O(V^2 log V), LINQ's OrderBy is not memoized or incremental, it is a fresh sort every time you enumerate it, easy to miss because the code reads as if it is just "getting the next item."
- ✓O(V+E) with Queue<T>; O((V+E) log V) with PriorityQueue<TElement, TPriority>, the same genuine (not just constant-factor) complexity step every language here pays for a canonical ordering, since C#'s PriorityQueue is also a binary heap under the hood.
What Topological Sort actually is
Topological Sort in C#: what you actually reach for
C# implementation
using System;
using System.Collections.Generic;
static class TopoSort
{
public static List<int> Order(Dictionary<int, List<int>> graph)
{
var indegree = new Dictionary<int, int>();
foreach (var node in graph.Keys) indegree.TryAdd(node, 0);
foreach (var nexts in graph.Values)
foreach (var next in nexts)
indegree[next] = indegree.GetValueOrDefault(next) + 1;
var queue = new Queue<int>(); // ring-buffer backed: O(1) Enqueue/Dequeue
foreach (var (node, d) in indegree) if (d == 0) queue.Enqueue(node);
var order = new List<int>(indegree.Count);
while (queue.Count > 0)
{
int node = queue.Dequeue();
order.Add(node);
foreach (int next in graph.GetValueOrDefault(node, new List<int>()))
{
indegree[next] -= 1;
if (indegree[next] == 0) queue.Enqueue(next);
}
}
if (order.Count != indegree.Count)
throw new InvalidOperationException("not a DAG: cycle present");
return order;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Topological Sort?
System.Collections.Generic.Queue<T> is the real, ring-buffer-backed FIFO (O(1) Enqueue/Dequeue), and System.Collections.Generic.PriorityQueue<TElement, TPriority>, added in .NET 6, is the real min-heap for a canonical or deterministic ordering, before .NET 6 there was no priority queue in the BCL at all, and people either hand-rolled a binary heap or reached for a third-party package.
What is the most common C# mistake when implementing Topological Sort?
Calling list.OrderBy(...).First() (or re-materializing an ordered list) inside the main loop to pick the next ready node re-sorts the entire remaining collection on every single iteration, turning what should be an O(V log V) priority-queue-based algorithm into O(V^2 log V), LINQ's OrderBy is not memoized or incremental, it is a fresh sort every time you enumerate it, easy to miss because the code reads as if it is just "getting the next item."
How does Topological Sort actually perform in C#?
O(V+E) with Queue<T>; O((V+E) log V) with PriorityQueue<TElement, TPriority>, the same genuine (not just constant-factor) complexity step every language here pays for a canonical ordering, since C#'s PriorityQueue is also a binary heap under the hood. Queue<T>.Dequeue() throws InvalidOperationException on an empty queue rather than returning a sentinel, so the emptiness check has to happen before the call, not be inferred from a return value the way some other languages' queue APIs allow. Time complexity is O(V+E) and space is O(V).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.