How to create hierarchical structure with list of path?

后端 未结 2 1380
长情又很酷
长情又很酷 2021-01-03 05:12

I\'m playing with the Dropbox\'s Delta API, when I call delta method I get a list of path\'s that changed since last call.

/photos 
/public 
/photos/sample a         


        
相关标签:
2条回答
  • 2021-01-03 05:40

    @casperOne solution is fine but it works with the list in the question only if you use

    char[] charSeparators = new char[] {'/'};
    

    rather then

    char[] charSeparators = new char[] {'\\'};
    
    0 讨论(0)
  • 2021-01-03 05:58

    It's a pretty simple parse operation. First, I'd define the class like so:

    public class Node
    {
        private readonly IDictionary<string, Node> _nodes = 
            new Dictionary<string, Node>();
    
        public string Path { get; set; }
    }
    

    From there it's a matter of:

    1. Parsing the path (using \ as the delimiter).
    2. Traversing down the tree, adding new nodes if necessary.

    You can wrap the above in a single method Add:

    public void AddPath(string path)
    {
       char[] charSeparators = new char[] {'\\'};
    
       // Parse into a sequence of parts.
       string[] parts = path.Split(charSeparators, 
           StringSplitOptions.RemoveEmptyEntries);
    
       // The current node.  Start with this.
       Node current = this;
    
       // Iterate through the parts.
       foreach (string part in parts)
       {
           // The child node.
           Node child;
    
           // Does the part exist in the current node?  If
           // not, then add.
           if (!current._nodes.TryGetValue(part, out child))
           {
               // Add the child.
               child = new Node {
                   Path = part
               };
    
               // Add to the dictionary.
               current._nodes[part] = child;
           }
    
           // Set the current to the child.
           current = child;
       }
    }
    

    This will give you the hierarchy you need. You can expose operations that work on the dictionary which will allow you to traverse it, but this is how you'd populate the general structure you'd be working with.

    Note that you'd start off with a singular node that has no Path and then iterate through your list above and call AddPath on every item in the list above.

    0 讨论(0)
提交回复
热议问题