首页 > 代码库 > LINQ获取树形分类的层数
LINQ获取树形分类的层数
数据库中的数据格式:
字段 | 数据类型 |
id | int |
department_pid | int |
department_name | nvarchar(20) |
- CREATE TABLE [dbo].[T_user_department](
- [id] [int] IDENTITY(1,1) NOT NULL,
- [department_pid] [int] NULL,
- [department_name] [nvarchar](20) NULL,
- CONSTRAINT [PK_T_USER_DEPARTMENT] PRIMARY KEY CLUSTERED
- (
- [id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- SET IDENTITY_INSERT [dbo].[T_user_department] ON
- INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (1, 0, N‘技术部‘)
- INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (2, 0, N‘ 销售部‘)
- INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (3, 2, N‘销售1部‘)
- INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (4, 2, N‘销售2部‘)
- INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (5, 0, N‘客服部‘)
- INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (6, 3, N‘人事部‘)
- SET IDENTITY_INSERT [dbo].[T_user_department] OFF
- ALTER TABLE [dbo].[T_user_department] ADD DEFAULT ((0)) FOR [department_pid]
树形格式(为了直观,按id排列)
1
2
3
6
4
5
获取层数的测试代码:
- #region
- // Admin/Account/Admin/GetDepartmentData
- public string GetDepartmentData(int id)
- {
- return GetLayerById(id).ToString();
- }
- /// <summary>
- /// 获取分类的层数
- /// </summary>
- /// <param name="id">根据id获取树的层数</param>
- /// <returns>树的层数</returns>
- private int GetLayerById(int id)
- {
- int layer = 1;
- for (int subId =(int)db.TUserDepartments.Where(d=>d.id==id).Select(d=>d.department_pid).ToList().FirstOrDefault(); subId != 0; )
- {
- subId = (int)db.TUserDepartments.Where(d => d.id == subId).Select(d => d.department_pid).ToList().FirstOrDefault();
- layer++;
- }
- return layer;
- }
- #endregion
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。