路径数据到树状数据结构

本文关键字:数据结构 数据 路径 | 更新日期: 2023-09-27 18:17:24

我有以下数据

root
root/blue
root/blue/temp
root/main
root/main/dev
root/main/back
root/etc/init
root/etc/init/dev
root/etc/init/test
root/etc/init/back
root/etc/init/server
root/etc/init/system
root/etc/init/setup
root/system
root/system/temp1
root/system/temp2
root/system/temp3
root/system/temp4
root/system/temp5
root/system/temp5/dev1
root/rel
root/intel/archival
root/intel/archival/newsreel
root/intel/archival/recording

我希望能够使用这个类来绑定到一个树控件(ASP.Net)或生成一个UL/Li供jquery使用。

我需要将其转换为一个List类,该类将返回适当的层次结构。到目前为止,我已经尝试了许多不同的方法,但我还没有找到一个解决方案。我卡住了。我试着问在较早的帖子,但解决方案没有工作,经过多次尝试修改一些它只是简单的不工作。我希望你们中有人能帮我。

这也不是一个简单的分割函数,我知道如何分割字符串。

提前感谢

路径数据到树状数据结构

下面是生成NodeEntry项嵌套字典的解决方案:

public class NodeEntry
{
    public NodeEntry()
    {
        this.Children = new NodeEntryCollection();
    }
    public string Key { get; set; }
    public NodeEntryCollection Children { get; set; }
}
public class NodeEntryCollection : Dictionary<string, NodeEntry>
{
    public void AddEntry(string sEntry, int wBegIndex)
    {
        if (wBegIndex < sEntry.Length)
        {
            string sKey;
            int wEndIndex;
            wEndIndex = sEntry.IndexOf("/", wBegIndex);
            if (wEndIndex == -1)
            {
                wEndIndex = sEntry.Length;
            }
            sKey = sEntry.Substring(wBegIndex, wEndIndex - wBegIndex);
            if (!string.IsNullOrEmpty(sKey)) {
                NodeEntry oItem;
                if (this.ContainsKey(sKey)) {
                    oItem = this[sKey];
                } else {
                    oItem = new NodeEntry();
                    oItem.Key = sKey;
                    this.Add(sKey, oItem);
                }
                // Now add the rest to the new item's children
                oItem.Children.AddEntry(sEntry, wEndIndex + 1);
            }
        }
    }
}

要使用上面的内容,创建一个新的集合:

        NodeEntryCollection cItems = new NodeEntryCollection();

然后,对于列表中的每一行:

        cItems.AddEntry(sLine, 0);