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