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

本文关键字:创建 层次结构 列表 路径 何使用 | 更新日期: 2023-09-27 18:36:05

我正在使用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 

我很难通过操作字符串来创建分层(在下面提到的类中)结构,任何人都可以提出一种可以实现它的方法/想法。

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

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

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

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

从那里开始,这是一个问题:

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

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

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

@casperOne解决方案很好,但仅当您使用

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

而不是然后

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