zoukankan      html  css  js  c++  java
  • 用树形结构递归渲染权限列表

    最近在用vue+.net core web api写前后端分离的权限系统,其中重要的一点就是关于权限列表渲染的问题了。常用的做法有字符串的拼接和树形结构的渲染,这里采用的是树形结构的渲染方式。在这里做一做技术分享,总结总结其中的重点

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

    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;
            }
  • 相关阅读:
    1、编写一个简单的C++程序
    96. Unique Binary Search Trees
    python 操作redis
    json.loads的一个很有意思的现象
    No changes detected
    leetcode 127 wordladder
    django uwsgi websocket踩坑
    you need to build uWSGI with SSL support to use the websocket handshake api function !!!
    pyinstaller 出现str error
    数据库的读现象
  • 原文地址:https://www.cnblogs.com/HTLucky/p/13822280.html
Copyright © 2011-2022 走看看