从文件夹位置列表创建对象层次结构

时间:2011-07-01 09:42:19

标签: c# string recursion linq-to-objects hierarchy

我有一个位置列表作为字符串;

locA/locB
locA/locB/locH
locC/locD/locE
locC/locD/locE/locK
locF/locG

我一直在尝试创建一个使用与传递给它的位置列表相同结构的对象;

e.g。像...这样的东西。

var myHObject=CreateHeirarchicalObjectFromList(myStringListOfLocations);

我在循环遍历列表时遇到问题而几乎没有手动加载循环。是否有更简单的方法,也许是递归?

我想最终得到像这样的对象;

.locA
    .locB
         .locH
.locC
    .locD
         .locE
              .locK
.locF
     .locG

我可以用来创建视觉层次结构。

1 个答案:

答案 0 :(得分:0)

Prob不是最好的,但在LinqPad中被击倒,将在一秒内重新格式化。

    void Main()
    {
        var strings = new string[]{"locA/locB","locA/locB/locH",
                         "locC/locD/locE","locC/locD/locE/locK","locF/locG"};

        var folders = Folder.Parse(strings);

        folders.Dump();
    }


    public class Folder
    {
        public string Name { get; set; }

        public List<Folder> Folders { get; internal set; }

        public Folder()
        {
            Folders = new List<Folder>();
        }
        //Presume that each string will be folder1/folder2/folder3
        public static IEnumerable<Folder> Parse(IEnumerable<string> locations)
        {
            var folders = new List<Folder>();
            foreach (string location in locations)
            {
                string[] parts = location.Split('/');
                Folder current = null;
                foreach (string part in parts)
                {
                    var useFolders = current != null ? 
                               current.Folders : folders;
                    current = useFolders.SingleOrDefault(f => f.Name == part) ?? new Folder() { Name = part };
                    if (!useFolders.Contains(current)) { useFolders.Add(current); }
                }
            }
            return folders;
        }
    }