我正在努力爲此代碼找到不同的方法。 我想創建一個下拉列表來選擇一個類別。 正如你可以看到它不乾淨,不適用於多個級別。 我不是.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