2012-06-03 66 views
3

我正在玩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>()); 
     } 
    } 
} 
+0

看起来你做了很好的工作。你还需要什么? –

+1

用于Java的[官方Dropbox SDK](https://www.dropbox.com/developers/reference/sdk)在“examples/SearchCache”中包含一个示例,该示例显示如何将结果从'/ delta'加载到树中结构体。 –

回答

7

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

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

0

@casperOne的解决方案是好的,但它与列表工作在这个问题只有在使用

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

而不是

char[] charSeparators = new char[] {'\\'}; 
+0

这不提供问题的答案。要批评或要求作者澄清,在他们的帖子下留下评论 - 你总是可以评论你自己的帖子,一旦你有足够的[声誉](http://stackoverflow.com/help/whats-reputation),你会能够[评论任何帖子](http://stackoverflow.com/help/privileges/comment)。 – Synchro

+0

我明白了,谢谢 – cinatic