C#用树形结构递归渲染权限列表

 

一.先写一个树形结构的工具类

复制代码
public class Tree
    {
        public int Id { set; get; }
        public int? ParentId { set; get; }
        public string Name { set; get; }
        public string Icon { get; set; }
        public string Path { get; set; }
        public int RoleId { get; set; }
        public string Description { get; set; }
        public IList<Tree> Children = new List<Tree>();
        public virtual void Addchildren(Tree node)
        {
            this.Children.Add(node);
        }

        public static IList<Tree> GetChildrens(Tree node, List<Tree> allList)
        {
            IList<Tree> childrens = allList.Where(x => x.ParentId == node.Id).ToList();
            foreach (Tree item in childrens)
            {
                item.Children = GetChildrens(item, allList);  //自己调用自己,通过递归的方式获取子类
            }
            return childrens;
        }
        public static IList<Tree> GetRoleChildren(Tree node, List<Tree> allList)
        {
            IList<Tree> childrens = allList.Where(x => x.ParentId == node.Id&&x.RoleId==node.RoleId).ToList();
            foreach (Tree item in childrens)
            {
                item.Children = GetRoleChildren(item, allList);  //自己调用自己,通过递归的方式获取子类
            }
            return childrens;
        }

    }
复制代码

二.借助树形结构渲染菜单列表

复制代码
public IList<Tree> GetMenuList()
        {
            //获取列表的全部信息
            List<Tree> list = DbContext.Modules.OrderBy(x => x.Weight).Select(x => new Tree { Id = x.Id, Name = x.Name, ParentId = x.ParentId, Icon = x.Icon, Path = x.Path }).ToList();
            //获取根元素
            List<Tree> rootNodes = list.Where(x => x.ParentId == 0).Select(x => new Tree { Id = x.Id, Name = x.Name, ParentId = x.ParentId, Icon = x.Icon }).ToList();
            foreach (Tree item in rootNodes)
            {
                //获取根元素下的所有子类
                item.Children = Tree.GetChildrens(item, list);
            }

            return rootNodes;
        }
复制代码

 

posted on   zyp_java_net  阅读(227)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示