简体   繁体   English

路径数据到树状数据结构

[英]path data to tree like data structure

i have the following data 我有以下数据

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

i would like to be able to use the class to either databind to a tree control (ASP.Net) or generate a UL/Li for jquery consumption. 我希望能够使用该类来数据绑定到树控件(ASP.Net)或生成用于jquery消耗的UL / Li。

I need to convert it to a List class that will return the proper hierarchy. 我需要将它转换为List类,它将返回适当的层次结构。 I have tried many different approach so far, and I'm not able to find a solution. 到目前为止,我尝试了很多不同的方法,但我无法找到解决方案。 I'm stuck. 我被卡住了。 I tried asking in an earlier post but the solution did not work, after many attempts to modify some it just plain does not work. 我尝试在较早的帖子中询问,但解决方案没有用,经过多次尝试修改一些它只是简单无效。 I hope one of you can help me out. 我希望你们中的一个可以帮助我。

Also this is not a simple split functions, I know how to split a string. 这也不是一个简单的拆分函数,我知道如何拆分字符串。

Thank you in advance 先感谢您

Here is a solution that generates a nested dictionary of NodeEntry items: 这是一个生成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);
            }
        }
    }
}

To use the above, create a new collection: 要使用上述内容,请创建一个新集合:

        NodeEntryCollection cItems = new NodeEntryCollection();

then, for each line in your list: 然后,对于列表中的每一行:

        cItems.AddEntry(sLine, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM