public dynamic GetDepartments(string labID) { List<int> usedIDs = new List<int>(); //缓存已用过的ID //定义递归算法 Func<object,List<DepartmentItem>, List<DepartmentItem>, dynamic> recursion = (r,d,a) => { List<dynamic> dyData = new List<dynamic>(); if (d.Count > 0) { d.ForEach(x => { if (!usedIDs.Contains(x.DepartmentID)) { dynamic department = new ExpandoObject(); department.DepartmentID = x.DepartmentID; department.DepartmentName = x.DepartmentName; department.DepartmentDesc = x.DepartmentDesc; department.CreateTime = x.CreateTime; department.ParentDepartmentID = x.ParentDepartmentID; usedIDs.Add(x.DepartmentID); // department.children = recursion(r, d, a); 这里直接调用的话会提示未定义变量,因为func的定义还没结束.. // 所以用以下的方法:调用的时候用object把方法传进来,然后转换下再调用执行; var func_recursion = r as Func<object, List<DepartmentItem>, List<DepartmentItem>, dynamic>; department.children = func_recursion(r, a.Where(w => w.ParentDepartmentID == x.DepartmentID).ToList(), a); dyData.Add(department); } }); } return dyData; }; var departments =.....//获取集合数据; //调用方法 //这里第一个参数就是方法的本身,传递进去进行递归调用 var result = recursion(recursion, departments, departments); return result; }
代码是将集合对象转换成树形结构