2012-06-03 64 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