如何使用路径列表创建层次结构?

Pra*_*dda 4 c# dropbox dropbox-api

我正在使用Dropbox的Delta API,当我调用delta方法时,我得到一个自上次调用后改变的路径列表.

/photos 
/public 
/photos/sample album 
/photos/sample album/boston city flow.jpg 
/photos/sample album/pensive parakeet.jpg 
/photos/sample album/costa rican frog.jpg 
/getting started.pdf 
/photos/how to use the photos folder.txt 
/public/how to use the public folder.txt 
/ies eai.pptx 
/documents 
/documents/windows phone toolkit in depth 2nd edition.pdf 
/prashant 
/prashant/iphone indexed list.bmml 
/photos/flower.jpg 
/photos/trs 
/photo.jpg 
/hello1 
/hello1/new 
Run Code Online (Sandbox Code Playgroud)

我很难通过操纵字符串来创建层次结构(在下面提到的类中)结构,任何人都可以建议我可以实现它的方式/想法.

public class DeltaItem
{

    private List<DeltaItem> _items;
    public string Path { get; set; }
    public bool IsDir { get; set; }

    public List<DeltaItem> Items
    {
        get
        {
            return _items ?? (_items = new List<DeltaItem>());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

cas*_*One 10

这是一个非常简单的解析操作.首先,我像这样定义类:

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

    public string Path { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

从那里它是一个问题:

  1. 解析路径(\用作分隔符).
  2. 遍历树,必要时添加新节点.

您可以将上述内容包装在一个方法中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;
   }
}
Run Code Online (Sandbox Code Playgroud)

这将为您提供所需的层次结构.您可以公开在字典上工作的操作,这将允许您遍历它,但这就是您填充您正在使用的常规结构的方式.

请注意,您将从一个没有的单个节点开始Path,然后遍历上面的列表并调用上面列表中的AddPath每个项目.