2017-05-05 39 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