数据结构~在页面上渲染树型结构
标准树的代码
1: class Tree 2: { 3: static Data.test.ICategoriesRepository iCategoriesRepository = new Data.test.CategoriesRepository(); 4: /// <summary> 5: /// 树形数据对象列表 6: /// </summary> 7: static List<Entity.test.Category> list = null; 8: /// <summary> 9: /// 获取当前树形数据对象列表 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: /// 重新加载分类树型列表 21: /// </summary> 22: internal static void Reload() 23: { 24: list = iCategoriesRepository.GetCategories().ToList(); 25: } 26: /// <summary> 27: /// 根据父对象,找到子孙树,通过递归所到所有子对象,并把对象赋给参数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); 树的显示时用到的递归方法 1: /// <summary> 2: /// 通过递归拼树形结构 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: }