tree状数据叶子节点与根节点等的递归转换
Posted taoshengyujiu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于tree状数据叶子节点与根节点等的递归转换的主要内容,如果未能解决你的问题,请参考以下文章