c# 枚举列表以从文件夹结构映射 parentId

c# Enumerate List to map parentId's from a folder structure

我有一个列表包含这个 class:

public class RazorTree
{
    public int id { get; set; }
    public string Name { get; set; }        
    public string Path { get; set; }
    public int? parentId { get; set; } = null;
}

示例:

id = 1
path = "C:\Projects\testapp\subdirectoy\"
name = "root"
parentId = null

id = 45
path = "C:\Projects\testapp\subdirectoy\test.razor"
name = "test"
parentId = null

id = 55
path = "C:\Projects\testapp\subdirectoy\subdirectory2\test.razor"
name = "test"
parentId = null

我需要的是带有 id = 45 的条目应该有 parentId = 1id = 55 应该有 parentId = 45 取决于每个条目的路径。

如何根据各自的路径 link children 和它们各自的 parent?

好的,以备将来参考。

这是我想出的:

public TreeItem GetFileStructure()
{
    var razorPages = typeof(Qassembly).Assembly.GetTypes().Where(x => x.BaseType?.Name == "LayoutComponentBase" || x.BaseType?.Name == "ComponentBase").ToList();

    var root = new TreeItem { Description = "root" ,Path = "root", ParentId = 0, Level =  4};

    List<string> TreePaths = new();

    foreach (var page in razorPages)
        TreePaths.Add(basePath + page.FullName.Replace(".", "\") + ".razor");

    foreach (var i in TreePaths)
        root.AddChild(i);

    return root;
}
        public class TreeItem
        {
            static List<TreeItem> FlatList = new List<TreeItem>();
            public TreeItem()
            {
                Id = FlatList.Any() ? FlatList.Max(m => m.Id) + 1 : 1;
                FlatList.Add(this);
                Children = new List<TreeItem>();
            }
            public string Description { get; set; }
            public string Path { get; set; }
            public int Id { get; set; }
            public int ParentId { get; set; }
            public int Level { get; set; }
            public List<TreeItem> Children { get; set; }

            public void AddChild(string Item)
            {
                var items = Item.Split('\');
                string path = string.Empty;
                for (int i = 0; i <= Level; i++)
                    path += (path == string.Empty ? string.Empty : "\") + items[i];

                if (path == Path)
                {
                    if ((Level + 1) == items.Count())
                        Children.Add(new TreeItem { Description = items[Level], Path = path, Level = Level + 1, ParentId = Id });
                    else
                    {
                        path += "\" + items[Level + 1];
                        var child = Children.FirstOrDefault(a => a.Path == path);
                        if (child == null)
                        {
                            child = new TreeItem { Description = path, Path = path, Level = Level + 1, ParentId = Id };
                            Children.Add(child);
                        }
                        child.AddChild(Item);
                    }

                }
            }
        }

这将从平面列表映射一棵树,即使每个 child 尚不知道 parentId。