2017-05-05 44 views
0

我正在努力为此代码找到不同的方法。 我想创建一个下拉列表来选择一个类别。 正如你可以看到它不干净,不适用于多个级别。 我不是.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; } 
} 

预先感谢您...

+1

谷歌为“递归函数” – Gusman

+0

请遵循以下准则问问题时, :http://stackoverflow.com/help/mcve。它使得它更容易帮助。 为了让任何人了解您的代码,您应该提供您的类别的类定义以及您的预期输入和输出 –

+0

@ J.N。我会说,在给出代码的情况下,OP是在寻找什么,这是一个递归函数。 – Steve

回答

1

好像你正在hierarchial树(使用"-""- -",等等)。

假设您的Categories是非循环的,您应该考虑使用递归函数来解决您的问题,在递归搜索中传递list以及您的打印前缀(“ - ”)或“深度”。

类似下面可能会成为:

public void addCatToList(List<SelectedItemList> list, int depth, IEnumerable<Category> cats){ 
    foreach (Category item in cats) 
    { 
     list.Add(new SelectListItem { Value = item .Id.ToString(), Text = printDash(depth) + item.Name }); 
     addCatToList(list, depth + 1, item.SubCategories); 
    } 

} 

private string printDash(int number){ 
    string dash = string.Empty; 
    for(int i = 0; i < number; ++i){ 
     if (i == 0) 
      dash += " "; 
     dash += "- "; 
    } 
    return dash; 
} 

然后调用它首次与depth = 0

List<SelectListItem> list = new List<SelectListItem>(); 
addCatToList(list, 0, db.CategorySet.Where(x => x.ParentCategory == null)); 
+0

非常感谢。 给我比特币地址,我给你买啤酒 –

+0

谢谢你的提议,弗兰克。尽管我没有比特币地址。 ;)此外,这里禁止帮助金融交易(AFAIK)。不用谢。 – Ian