首页 > 代码库 > LINQ获取树形分类的层数

LINQ获取树形分类的层数

数据库中的数据格式:

字段 数据类型
id int
department_pid int
department_name nvarchar(20)

 

 
  1. CREATE TABLE [dbo].[T_user_department](  
  2.     [id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [department_pid] [intNULL,  
  4.     [department_name] [nvarchar](20) NULL,  
  5.  CONSTRAINT [PK_T_USER_DEPARTMENT] PRIMARY KEY CLUSTERED   
  6. (  
  7.     [id] ASC 
  8. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  9. ON [PRIMARY]  
  10.  
  11. SET IDENTITY_INSERT [dbo].[T_user_department] ON 
  12. INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (1, 0, N‘技术部‘)  
  13. INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (2, 0, N‘ 销售部‘)  
  14. INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (3, 2, N‘销售1部‘)  
  15. INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (4, 2, N‘销售2部‘)  
  16. INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (5, 0, N‘客服部‘)  
  17. INSERT [dbo].[T_user_department] ([id], [department_pid], [department_name]) VALUES (6, 3, N‘人事部‘)  
  18. SET IDENTITY_INSERT [dbo].[T_user_department] OFF 
  19.  
  20. ALTER TABLE [dbo].[T_user_department] ADD  DEFAULT ((0)) FOR [department_pid]  
  21.  

树形格式(为了直观,按id排列)

1

2

  3

      6

  4

5

获取层数的测试代码:

 
  1. #region  
  2.         // Admin/Account/Admin/GetDepartmentData  
  3.         public string GetDepartmentData(int id)  
  4.         {  
  5.             return GetLayerById(id).ToString();  
  6.         }  
  7.  
  8.  
  9.         /// <summary>  
  10.         /// 获取分类的层数  
  11.         /// </summary>  
  12.         /// <param name="id">根据id获取树的层数</param>  
  13.         /// <returns>树的层数</returns>  
  14.         private int GetLayerById(int id)  
  15.         {  
  16.             int layer = 1;  
  17.             for (int subId =(int)db.TUserDepartments.Where(d=>d.id==id).Select(d=>d.department_pid).ToList().FirstOrDefault(); subId != 0; )  
  18.             {  
  19.                 subId = (int)db.TUserDepartments.Where(d => d.id == subId).Select(d => d.department_pid).ToList().FirstOrDefault();  
  20.                 layer++;  
  21.             }  
  22.             return layer;  
  23.         }  
  24.         #endregion