Created
February 2, 2020 07:21
-
-
Save ericoporto/17cf45a3112098cedb150d13828f9415 to your computer and use it in GitHub Desktop.
Topological Sorting in C# from SO -> https://stackoverflow.com/questions/4106862/how-to-sort-depended-objects-by-dependency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static IEnumerable<T> TSort<T>( this IEnumerable<T> source, Func<T, IEnumerable<T>> dependencies, bool throwOnCycle = false ) | |
{ | |
var sorted = new List<T>(); | |
var visited = new HashSet<T>(); | |
foreach( var item in source ) | |
Visit( item, visited, sorted, dependencies, throwOnCycle ); | |
return sorted; | |
} | |
private static void Visit<T>( T item, HashSet<T> visited, List<T> sorted, Func<T, IEnumerable<T>> 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" ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment