.net list转树状结构

主要的方法

 1        /// <summary>
 2         /// 转化成树结构
 3         /// </summary>
 4         /// <param name="menuList">菜单的平级list</param>
 5         /// <returns></returns>
 6         private List<AbpMenuModel> GetTreeParent(List<AbpMenuDto> menuList)
 7         {
 8             var dic = new Dictionary<long, AbpMenuModel>(menuList.Count);
 9             foreach (var chapter in menuList)
10             {
11                 dic.Add(chapter.Id, new AbpMenuModel { Id = chapter.Id, Title = chapter.Title, Path = chapter.Path, ParentId = chapter.ParentId, Icon = chapter.Icon });
12             }
13             foreach (var chapter in dic.Values)
14             {
15                 if (dic.ContainsKey(chapter.ParentId.Value))
16                 {
17                     if (dic[chapter.ParentId.Value].Children == null)
18                     {
19                         dic[chapter.ParentId.Value].Children = new List<AbpMenuModel>();
20 
21                     }
22                     dic[chapter.ParentId.Value].Children.Add(chapter);
23                 }
24             }
25             return dic.Values.Where(t => t.ParentId == 0).ToList();
26         }

 

转换前的类

    [AutoMapTo(typeof(AbpMenuDto))]
    public class AbpMenuDto : EntityDto<long>
    {
        /// <summary>
        /// 路径
        /// </summary>
        public string Path { get; set; }
        /// <summary>
        /// 菜单名
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 图标
        /// </summary>
        public string Icon { get; set; }

        /// <summary>
        /// 父级ID
        /// </summary>
        public long? ParentId { get; set; }
        /// <summary>
        /// 类型  菜单(menu) 还是  元素(doc)(按钮等)
        /// </summary>
        public string Type { get; set; }
        /// <summary>
        ///  doc时 的父级下唯一代码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        ///  doc时 的名称
        /// </summary>
        public string Name { get; set; }
    }

 

转换后的类

 public class AbpMenuModel : EntityDto<long>
    {
        /// <summary>
        /// 路径
        /// </summary>
        public string Path { get; set; }
        /// <summary>
        /// 菜单名
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 图标
        /// </summary>
        public string Icon { get; set; }

        /// <summary>
        /// 父级ID
        /// </summary>
        public long? ParentId { get; set; }
        /// <summary>
        /// 类型  菜单(menu) 还是  元素(doc)(按钮等)
        /// </summary>
        public string Type { get; set; }
        /// <summary>
        ///  doc时 的父级下唯一代码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        ///  doc时 的名称
        /// </summary>
        public string Name { get; set; }

        public List<AbpMenuModel> Children { get; set; }

 

posted @ 2019-07-23 18:39  老李的自我救赎之路。  阅读(515)  评论(0编辑  收藏  举报