递归权限树的实现
1
/// <summary> /// 角色权限Model /// </summary> public class RoleRightBllModel { /// <summary> /// 权限Id /// </summary> public int RightId { get; set; } /// <summary> /// 权限名称 /// </summary> public string RightName { get; set; } /// <summary> /// 权限(由Crud的权限按位或生成) /// </summary> public int Right { get; set; } /// <summary> /// 子权限 /// </summary> public IEnumerable<RoleRightBllModel> SubRights { get; set; } }
2
/// <summary> /// 角色权限Model /// </summary> public class RoleRightModel { /// <summary> /// Id /// </summary> public int Id { get; set; } /// <summary> /// 角色Id /// </summary> public int RoleId { get; set; } /// <summary> /// 权限Id /// </summary> public int RightId { get; set; } /// <summary> /// 权限名称 /// </summary> public string RightName { get; set; } /// <summary> /// 父权限Id /// </summary> public int ParentRightId { get; set; } /// <summary> /// 权限(由Crud的权限按位或生成) /// </summary> public int Right { get; set; } }
3.
public static class RightHelper { public static IList<RoleRightBllModel> GetRoleRights(this IEnumerable<RoleRightModel> roleRightModels, int parentRightId = 0) { if (roleRightModels == null) { return null; } var result = roleRightModels.Where(p => p.ParentRightId == parentRightId).Select(p => new RoleRightBllModel() { Right = p.Right, RightId = p.RightId, RightName = p.RightName, SubRights = null }).ToList(); foreach (var item in result) { var sub = roleRightModels.Where(p => p.ParentRightId == item.RightId); if (sub.Any()) { item.SubRights = roleRightModels.GetRoleRights(item.RightId); } } return result; } }
4.调用代码]
public class RightTest { public static void Execute() { var rights = new List<RoleRightModel> { { new RoleRightModel() { Id=1, RoleId = 1001, Right = 7, RightId = 1, RightName = "权限1", ParentRightId = 0 } }, { new RoleRightModel() { Id=2, RightId = 2, RoleId = 1001, Right = 7, RightName = "权限2", ParentRightId = 0 } }, { new RoleRightModel() { Id=12, RightId = 12, RoleId = 1001, Right = 7, RightName = "权限12", ParentRightId = 1 } }, { new RoleRightModel() { Id=13, RightId = 13, RoleId = 1001, Right = 7, RightName = "权限13", ParentRightId = 1 } }, { new RoleRightModel() { Id=102, RightId = 102, RoleId = 1001, Right = 7, RightName = "权限120", ParentRightId = 12 } }, { new RoleRightModel() { Id=103, RightId = 103, RoleId = 1001, Right = 7, RightName = "权限130", ParentRightId = 13 } }, }; var roleRights = rights.GetRoleRights(0); Console.WriteLine(roleRights.ToJsonStr()); Console.Read(); } }
5.输出代码