我正在努力为此代码找到不同的方法。 我想创建一个下拉列表来选择一个类别。 正如你可以看到它不干净,不适用于多个级别。 我不是.NET专家,想了解专业人士如何做到这一点。嵌套的foreach用于自引用表
List<SelectListItem> list = new List<SelectListItem>();
foreach (Category item in db.CategorySet.Where(x => x.ParentCategory == null))
{
list.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Name });
foreach (Category subitem in item.SubCategories)
{
list.Add(new SelectListItem { Value = subitem.Id.ToString(), Text = " - " + subitem.Name });
foreach (Category subsubitem in subitem.SubCategories)
{
list.Add(new SelectListItem { Value = subsubitem.Id.ToString(), Text = " - - " + subsubitem.Name });
foreach (Category subsubsubitem in subsubitem.SubCategories)
{
list.Add(new SelectListItem { Value = subsubsubitem.Id.ToString(), Text = " - - - " + subsubsubitem.Name });
//...
}
}
}
}
public partial class Category
{
public Category()
{
this.Products = new HashSet<Product>();
this.SubCategories = new HashSet<Category>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public Nullable<int> ParentCategoryId { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Category> SubCategories { get; set; }
public virtual Category ParentCategory { get; set; }
}
预先感谢您...
谷歌为“递归函数” – Gusman
请遵循以下准则问问题时, :http://stackoverflow.com/help/mcve。它使得它更容易帮助。 为了让任何人了解您的代码,您应该提供您的类别的类定义以及您的预期输入和输出 –
@ J.N。我会说,在给出代码的情况下,OP是在寻找什么,这是一个递归函数。 – Steve