Page cover image

Topological Sorting

TopoSort is a static class that provides functionality to perform a topological sort on a collection of items with dependencies.

Sort

This method takes a source collection of items and a function that returns the dependencies of each item. It returns a sorted list of items based on their dependencies.

Example:

var items = new List<string> { "A", "B", "C", "D" };
var dependencies = new Dictionary<string, List<string>>
{
    { "A", new List<string> { "B", "C" } },
    { "B", new List<string> { "C", "D" } },
    { "C", new List<string> { "D" } },
    { "D", new List<string>() }
};

var sortedItems = TopoSort.Sort(items, item => dependencies[item]);
// sortedItems will be ["D", "C", "B", "A"]

Last updated