C# 如何在MVC.Net中为无限类别树编写Foreach循环?

C# 如何在MVC.Net中为无限类别树编写Foreach循环?,c#,asp.net-mvc,entity-framework,linq,C#,Asp.net Mvc,Entity Framework,Linq,类别表: CategoryId (int) PK ParentCategoryId (int) FK CategoryName 。。。当然,它不会生成类别树 下面是一个递归解决方案的近似值: 在你看来: @WriteChilds(null, "") 这是方法体,我相信您可以将Console.WriteLine转换为html输出: public void WriteChilds(int? ParentCategoryId, string parentName) { var c

类别表:

 CategoryId (int) PK 
 ParentCategoryId (int) FK
 CategoryName


。。。当然,它不会生成类别树

下面是一个递归解决方案的近似值:

在你看来:

@WriteChilds(null, "")
这是方法体,我相信您可以将Console.WriteLine转换为html输出:

public void WriteChilds(int? ParentCategoryId, string parentName) {
    var categories = Model.Where(a => a.parentCategoryId == ParentCategoryId);
    foreach(var category in categories) {
        Console.WriteLine(parentName + " " + category.CategoryName);
        WriteChilds(category.CategoryId, category.CategoryName);
    }
}

如果树的深度(理论上)是无限的,那么一个简单的循环将不起作用,你需要使用递归。如果你不理解递归,就研究它。mnieto下面的方法为您提供了结构,您只需要调整它以生成HTML。
@WriteChilds(null, "")
public void WriteChilds(int? ParentCategoryId, string parentName) {
    var categories = Model.Where(a => a.parentCategoryId == ParentCategoryId);
    foreach(var category in categories) {
        Console.WriteLine(parentName + " " + category.CategoryName);
        WriteChilds(category.CategoryId, category.CategoryName);
    }
}