目录路径的递归

时间:2019-04-03 06:47:07

标签: c# asp.net asp.net-mvc asp.net-core

这是我的目录模型

resources/assets/js/components

这就是我检索目录树的方式。

public class Repositories
{
    public string Id { get; set; }
    public string ParentId { get; set; }
    public string Name { get; set; }
    public string ApplicationName { get; set; }
    public string ApplicationId { get; set; }
    public string Path { get; set; }
    public ICollection<Repositories> RepositoryObjectChildren { get; set; }
    public DateTime CreatedOn { get; set; }
}

我不确定如何从这里继续。如何保存到该模型?具体来说,如何保存到ICollection部分?我的意图是使用可能包含子文件夹的子文件夹创建文件夹目录。

1 个答案:

答案 0 :(得分:0)

根据上面的评论,这是一个工作示例,说明如何递归遍历“平面”列表。我将保持基本状态,您可以将其应用于您的特定用例。

//my test class for the 'flat' folder structure
public class Item
{
    public string Id { get; set; }
    public string ParentId { get; set; }
    public string title { get; set; }
    public List<Item> subs { get; set; }

    public Item()
    {
        this.Id = "";
        this.ParentId = "";
        this.title = "";
        this.subs = new List<Item>();
    }
}

//example using MVC controller
public class YourController : Controller
{
    //var to hold all the 'flat' data
    private List<Item> fulllist = new List<Item>();

    //recursive method to loop through the flat list
    public List<Item> GetChildren(string parentId)
    {
        List<Item> result = new List<Item>();

        foreach (Item child in fulllist.Where(n=>n.ParentId == parentId))
        {
            child.subs = GetChildren(child.Id);
            result.Add(child);
        }

        return result;
    }

    [HttpGet]
    public ActionResult Index()
    {
        //populate the flat list with test data (multi-level)
        fulllist.Add(new Item()
        {Id = "1", ParentId = "", title = "main 1"});
        fulllist.Add(new Item()
        {Id = "2", ParentId = "", title = "main 2"});
        fulllist.Add(new Item()
        {Id = "3", ParentId = "1", title = "main 1 - sub 1"});
        fulllist.Add(new Item()
        {Id = "4", ParentId = "", title = "main 3"});
        fulllist.Add(new Item()
        {Id = "5", ParentId = "4", title = "main 3 - sub 1"});
        fulllist.Add(new Item()
        {Id = "6", ParentId = "5", title = "main 3 - sub 1 - subsub 1"});
        fulllist.Add(new Item()
        {Id = "7", ParentId = "", title = "main 4"});
        fulllist.Add(new Item()
        {Id = "8", ParentId = "7", title = "main 4 - sub 1"});

        //get from the start of the tree
        var output = GetChildren("");

        return Json(output, JsonRequestBehavior.AllowGet);
    }
}