c#递归读取菜单树

1.查询菜单节点下所有子节点id

List<sys_module> menus = new List<sys_module>() { };

public async Task<PostResult<int>> DeleteModule(int? id)
{
return await Task.Run(() =>
{
var cnt = 1;
var childids = new List<int?>() { id };
var list = db.Queryable<sys_module>().Where(c => c.isdel == "N").ToList();
foreach (var item in list.FindAll(c => c.parentid == id))
{
menus.Add(item);
FillMenu(item, list);
}
foreach (var i in menus)
{
childids.Add(i.id);
}
if (childids.Any())
{
cnt = db.Updateable<sys_module>().UpdateColumns(c => new sys_module() { isdel = "Y" }).Where(c => childids.Contains(c.id)).ExecuteCommand();
}
return new PostResult<int>
{
data = cnt,
msg = "success"
};
});
}

private void FillMenu(sys_module node, List<sys_module> list)
{
foreach (var i in list.FindAll(i => i.parentid == node.id))
{
menus.Add(i);
FillMenu(i, list);
}
}


2.查询用户授权的菜单树,(根据用户角色,查询角色关联的菜单树)

<hr />

private Tuple<List<string>, List<SysMenuTree>, List<string>> GetModel(sys_user user)
{
var roles = new List<string> { "管理员", "普通用户" };//用户角色
var menutrees = new List<SysMenuTree> { };//用户菜单树
var permissions = new List<string> { "user_add", "user_edit" };//接口授权标识

var relations = db.Queryable<sys_relevance>().Where(c => c.isdel == "N").ToList();
var userroles = relations.Where(c => c.key.Equals("UserRole") &amp;&amp; c.firstid == user.id).Select(c => c.secondid).ToList();
roles = db.Queryable<sys_role>().Where(c => c.isdel == "N" &amp;&amp; userroles.Contains(c.id)).Select(c => c.name).ToList();

var rolemenus = relations.Where(c => c.key.Equals("RoleModule") &amp;&amp; userroles.Contains(c.firstid)).Select(c => c.secondid).ToList();
var menus = db.Queryable<sys_module>().Where(c => c.isdel == "N" &amp;&amp; c.status == "Y" &amp;&amp; rolemenus.Contains(c.id)).ToList(); ;

permissions = menus.Where(c => !string.IsNullOrEmpty(c.authorize)).Select(c => c.authorize).Distinct().ToList();

var list = menus.FindAll(c => c.type != 2);
var trees = new List<SysMenuTree>() { };
foreach (var i in list.FindAll(c => c.parentid == -1))
{
var nodel = new SysMenuTree() { id = i.id, name = i.name, parentid = i.parentid, icon = i.icon, url = i.url, path = i.path };
trees.Add(nodel);
FillTree(nodel, list);
}
menutrees = trees;

return Tuple.Create(roles, menutrees, permissions);
}

private void FillTree(SysMenuTree node, List<sys_module> list)
{
if (list.Any(m => m.parentid == node.id))
{
node.subMenus = new List<SysMenuTree>() { };
}
foreach (var i in list.FindAll(i => i.parentid == node.id))
{
var subnode = new SysMenuTree()
{
id = i.id,
name = i.name,
parentid = i.parentid,
icon = i.icon,
url = i.url,
path = i.path,
};
node.subMenus.Add(subnode);
FillTree(subnode, list);
}
}

 

posted @ 2019-02-27 20:11  胡椒面  阅读(702)  评论(0编辑  收藏  举报