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

标签 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 

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

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

关于c# - 如何使用路径列表创建层次结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10870443/

相关文章:

java - 如何格式化我从 Dropbox 元数据调用到自定义表单中获得的时间戳?

包含可折叠递归目录列表的 HTML

python - 如何获取和使用 Dropbox API 的刷新 token (Python 3.x)

java - Android DropBox 登录问题

c# - 用 C# 在 asp.net 中拆分字符串

c# - 用于获取子元素计数的 XPath 表达式

c# - 使用 System.IO.Compression 压缩完整文件夹

c# - 存储邮件模板的推荐做法

android - 设置 Android 项目以使用 git

file-upload - DropboxSDK : What's the benefit of uploadFileChunk: over uploadFile: in DBRestClient?