簡體   English   中英

如何使用路徑列表創建層次結構?

[英]How to create hierarchical structure with list of path?

我正在使用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[] {'\\'};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM