• tree状数据叶子节点与根节点等的递归转换


    做项目时经常遇到树状层级数据。从各个层级数据的转换查询等。场景如行业类别的多层级,行政区层级,检查项类别层级等等。

    数据结构如  Id Name ParentId

     #region area树状节点的转化
    
            public List<Area> ConvertToLeafChildAreas(List<int> areaIds)
            {
                var allAreas = GetNewAreas().ToList();
                List<Area> leafChildren = new List<Area>();
                foreach (var areaId in areaIds)
                {
                    leafChildren.AddRange(GetLeafChildAreas(areaId, allAreas));
                }
                return leafChildren;
            }
    
            /// <summary>
            /// 根据父ID获取所有的最小地区
            /// </summary>
            /// <param name="parentId"></param>
            /// <param name="allAreas"></param>
            /// <returns></returns>
            public List<Area> GetLeafChildAreas(int parentId,List<Area> allAreas)
            {
                List<Area> leafChildren = new List<Area>();
                var sons = allAreas.Where(o => o.ParentId == parentId).ToList();
                if (sons.Any())
                {
                    foreach (var item in sons)
                    {
                        leafChildren.AddRange(GetLeafChildAreas(item.Id, allAreas));
                    }
                }
                else
                {
                    var currentArea = allAreas.FirstOrDefault(m=>m.Id== parentId);
                    leafChildren.Add(currentArea);
                }
                return leafChildren;
            }
    
            public List<Area> ConvertToRootAreas(List<int> childAreaIds)
            {
                var allAreas = GetNewAreas().ToList();
                var childAreas = allAreas.Where(m => childAreaIds.Contains(m.Id)).ToList();
                List<Area> root = new List<Area>();
                foreach (var childArea in childAreas)
                {
                    root.Add(GetRootArea(childArea, allAreas));
                }
                return root.Distinct().ToList();
            }
            /// <summary>
            /// 根据子ID获取所有的最顶级地区
            /// </summary>
            /// <param name="childArea"></param>
            /// <param name="allAreas"></param>
            /// <returns></returns>
            public Area GetRootArea(Area childArea, List<Area> allAreas)
            {
                var parentArea = allAreas.FirstOrDefault(o => o.Id == childArea.ParentId);
                if (parentArea==null) return childArea;
                return GetRootArea(parentArea,allAreas);
            }
            #endregion
    

      

  • 相关阅读:
    table表头固定
    【ztree系列——图标的修改】Bootstrap风格的ztree
    JS使用cookie实现DIV提示框只显示一次的方法
    js正则验证手机号码有效性
    Highcharts、AJAX、JSON、JQuery实现动态数据交互显示图表柱形图
    display:table合并表格
    jsp标签、 项目全路径引用${ctx}
    apache poi合并单元格设置边框
    Kettle 中转换(transformation)的执行过程
    数据结构--堆的实现(上)
  • 原文地址:https://www.cnblogs.com/taoshengyujiu/p/10061819.html
Copyright © 2020-2023  润新知