How to sort depended objects by dependency

后端 未结 10 545
青春惊慌失措
青春惊慌失措 2020-11-28 19:31

I have a collection:

List> dependencyHierarchy;

The first item in pair is some object (item) and the

10条回答
  •  一生所求
    2020-11-28 19:55

    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" );
        }
    }
    

提交回复
热议问题