I found an excellent article on Topological Sorting in C#. The class is pretty easy to understand and the article is excellent.
Why is this useful? Consider a data synchronization project that needs to distribute data to various systems. The order in which jobs execute matter because reference data has dependencies on one or more master data items, at potentially different levels in the hierarchy. Having a simple SortOrder property quickly becomes insufficient and difficult to manage for large job sets.
By performing a topological sort you can get the first group of items that have no dependency, the second group which depends on the first, and so on. The problem is reduced to a statement that looks like this:
//Get the groups var groups = TopologicalSort.Group(Jobs, x => x.DependentOn, x => x.Id); //Sort by the SortOrder property and return the groups return groups.Select(x => x.Select(y => y).OrderBy(z => z.SortOrder ?? 0).ToList()).ToList();
Now your admin only has to set the dependency and trust that the system will find the correct execution order, in my example I added SortOrder for a little more tweaking. You as the developer can now focus on more interesting topics like parallel execution per group. 🙂
Check out the article and code at: