數據結構~在頁面上渲染樹(shu)型結構
標準樹的代碼
1: class Tree 2: { 3: static Data.test.ICategoriesRepository iCategoriesRepository = new Data.test.CategoriesRepository(); 4: /// <summary> 5: /// 樹形數據(ju)對(dui)象(xiang)列表 6: /// </summary> 7: static List<Entity.test.Category> list = null; 8: /// <summary> 9: /// 獲取當(dang)前樹形數據對(dui)象列表(biao) 10: /// </summary> 11: internal static List<Entity.test.Category> ProductVirtualCategoryList 12: { 13: get { return list; } 14: } 15: static Tree() 16: { 17: Reload(); 18: } 19: /// <summary> 20: /// 重(zhong)新加載(zai)分類樹(shu)型(xing)列表 21: /// </summary> 22: internal static void Reload() 23: { 24: list = iCategoriesRepository.GetCategories().ToList(); 25: } 26: /// <summary> 27: /// 根據父對象,找到子孫樹,通(tong)過遞歸所(suo)到所(suo)有子對象,并(bing)把對象賦給參數(shu)father 28: /// </summary> 29: /// <param name="father">父對象</param> 30: static internal void GetSublCategories(Entity.test.Category father) 31: { 32: father.SubCategoryies = list.Where(item => item.ParentId.Equals(father.Id)).ToList(); 33: father.SubCategoryies.ForEach(item => {item.FatherCategory = father; 34: GetSublCategories(item); 35: }); 36: } 37: }
1: #region 樹的遍歷(遞歸思想) 2: Entity.test.Category list = new Entity.test.Category { Id = 1 }; 3: Tree.GetSublCategories(list);//為list填充子樹 4: StringBuilder html = new StringBuilder(); 5: html.Append("<ul>"); 6: GetSubCategory(html, list); 7: html.Append("</ul>"); 8: #endregion 9: Console.WriteLine(html); 樹(shu)的顯示時(shi)用到(dao)的遞(di)歸方法 1: /// <summary> 2: /// 通(tong)過遞歸拼樹(shu)形結構 3: /// </summary> 4: /// <param name="html"></param> 5: /// <param name="category"></param> 6: private static void GetSubCategory(StringBuilder html, Entity.test.Category category) 7: { 8: html.Append("<li>"); 9: html.Append("<input type='hidden' value='" + category.Id + "' />"); 10: html.Append("<a href='#' name='" + category.Name + "'>"); 11: html.Append("<ins> </ins>"); 12: html.Append(category.Id + "-" + category.Name + "(" + category.Level + ")"); 13: html.Append("</a>"); 14: if (category.SubCategoryies != null && category.SubCategoryies.Count > 0) 15: { 16: html.Append("<ul>"); 17: foreach (var item in category.SubCategoryies) 18: { 19: GetSubCategory(html, item); 20: } 21: html.Append("</ul>"); 22: } 23: html.Append("</li>"); 24: }