How to (Efficiently) Sort a List of Items with Parent/Child Relationship
I think you already have implemented some sort of adjacency list representation of a directed graph. You can use a topological sorting (https://en.m.wikipedia.org/wiki/Topological_sorting) to order the items.