| | | 1 | | // ReSharper disable once CheckNamespace |
| | | 2 | | namespace Elsa.Extensions; |
| | | 3 | | |
| | | 4 | | /// <summary> |
| | | 5 | | /// Adds extension methods to sort collections by their dependencies, also known as a topological sort. |
| | | 6 | | /// </summary> |
| | | 7 | | public static class EnumerableTopologicalSortExtensions |
| | | 8 | | { |
| | | 9 | | /// <summary> |
| | | 10 | | /// Returns a topologically sorted copy of the specified list. |
| | | 11 | | /// </summary> |
| | | 12 | | // ReSharper disable once InconsistentNaming |
| | | 13 | | public static IEnumerable<T> TSort<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> dependencies, bool throwOn |
| | | 14 | | { |
| | 3 | 15 | | var sorted = new List<T>(); |
| | 3 | 16 | | var visited = new HashSet<T>(); |
| | | 17 | | |
| | 42 | 18 | | foreach (var item in source) |
| | 18 | 19 | | Visit(item, visited, sorted, dependencies, throwOnCycle); |
| | | 20 | | |
| | 3 | 21 | | return sorted; |
| | | 22 | | } |
| | | 23 | | |
| | | 24 | | private static void Visit<T>(T item, ISet<T> visited, ICollection<T> sorted, Func<T, IEnumerable<T>> dependencies, b |
| | | 25 | | { |
| | 40 | 26 | | if (visited.Add(item)) |
| | | 27 | | { |
| | 82 | 28 | | foreach (var dep in dependencies(item)) |
| | 22 | 29 | | Visit(dep, visited, sorted, dependencies, throwOnCycle); |
| | | 30 | | |
| | 19 | 31 | | sorted.Add(item); |
| | | 32 | | } |
| | | 33 | | else |
| | | 34 | | { |
| | 21 | 35 | | if (throwOnCycle && !sorted.Contains(item)) |
| | 0 | 36 | | throw new Exception("Cyclic dependency found"); |
| | | 37 | | } |
| | 21 | 38 | | } |
| | | 39 | | } |