I have a collection:
List> dependencyHierarchy;
The first item in pair is some object (item) and the
Having struggled with this for a while, here's my attempt at a Linq style TSort extension method:
public static IEnumerable TSort( this IEnumerable source, Func> dependencies, bool throwOnCycle = false )
{
var sorted = new List();
var visited = new HashSet();
foreach( var item in source )
Visit( item, visited, sorted, dependencies, throwOnCycle );
return sorted;
}
private static void Visit( T item, HashSet visited, List sorted, Func> dependencies, bool throwOnCycle )
{
if( !visited.Contains( item ) )
{
visited.Add( item );
foreach( var dep in dependencies( item ) )
Visit( dep, visited, sorted, dependencies, throwOnCycle );
sorted.Add( item );
}
else
{
if( throwOnCycle && !sorted.Contains( item ) )
throw new Exception( "Cyclic dependency found" );
}
}