1. 程式人生 > >tree狀資料葉子節點與根節點等的遞迴轉換

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