• 记一则 Lambda内递归调用方法将集合对象转换成树形结构


     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;
    
            }
    

      代码是将集合对象转换成树形结构

  • 相关阅读:
    2d向量类 —— js版
    多边形碰撞demo —— 小车撞墙壁
    真累啊——近一年的工作心得
    重力感应相关api
    坐标旋转
    判断web app是否从主屏启动
    “简单就是力量”、“重构”和“架构设计”
    多边形碰撞算法
    《是男人就下一百层》游戏小demo
    优秀的接口的评价标准
  • 原文地址:https://www.cnblogs.com/yesicoo/p/10947161.html
Copyright © 2020-2023  润新知