最近工作中涉及到菜单,各种递归.总结了2种.
按父级子级生成树
public async Task<List<ResourceDirectorysListTreeDto>> GetTreeByParentId(long id, int getChildCount = 0) { var menuAll = _ResourceDirectorysRepository.GetAll().Where(zz => zz.IsDeleted == false); var menuRoot = await _ResourceDirectorysRepository.GetAll().Where(zz => zz.ParentId == id && zz.IsDeleted == false).ToListAsync(); var menuList = ObjectMapper.Map<List<ResourceDirectorysListTreeDto>>(menuRoot); // 为一级菜单设置子菜单,getChild是递归调用的 foreach (var item in menuList) { item.Child = GetChild(item.Id, menuAll.ToList(), 1, getChildCount); } return menuList; } private List<ResourceDirectorysListTreeDto> GetChild(long id, List<EntityDesign.Resourses.ResourceDirectorys> menuAll, int excouteCout, int getChildCount) { if (getChildCount > 0 && excouteCout > getChildCount) { return null; } //子菜单 List<ResourceDirectorysListTreeDto> childList = new List<ResourceDirectorysListTreeDto>(); // 遍历所有节点,将父菜单id与传过来的id比较 var list = menuAll.Where(x => x.ParentId == id).ToList(); if (!list.Any()) { return null; } foreach (var item in list) { if (item.ParentId == id) { childList.Add(new ResourceDirectorysListTreeDto { Id = item.Id, ParentId = item.ParentId, Name = item.Name, IndexLevel = item.IndexLevel }); } } // 把子菜单的子菜单再循环一遍 foreach (var item in childList) { item.Child = GetChild(item.Id, menuAll, excouteCout + 1, getChildCount); } // 递归退出条件 if (childList.Count == 0) { return null; } return childList; }
按父级子级生成List
public async Task<List<ResourceDirectorysListDto>> GetAllListByParentId(long id) { var menuRoot = await _ResourceDirectorysRepository.GetAll().Where(zz => zz.ParentId == id && zz.IsDeleted == false).ToListAsync(); var menuList = ObjectMapper.Map<List<ResourceDirectorysListDto>>(menuRoot); // 为一级菜单设置子菜单,getChild是递归调用的 var temp = new List<ResourceDirectorysListDto>(); foreach (var item in menuList) { temp.Add(item); var t = GetChild2(item.Id); if (t != null) { item.IsParent = true; temp.AddRange(t); } else { item.IsParent = false; } } return temp; } private List<ResourceDirectorysListDto> GetChild2(long id) { //子菜单 List<ResourceDirectorysListDto> childList = new List<ResourceDirectorysListDto>(); // 遍历所有节点,将父菜单id与传过来的id比较 var list = _ResourceDirectorysRepository.GetAll().Where(x => x.ParentId == id).ToList(); if (!list.Any()) { return null; } foreach (var item in list) { if (item.ParentId == id) { var z = new ResourceDirectorysListDto { Id = item.Id, ParentId = item.ParentId, Name = item.Name, }; childList.Add(z); var t = GetChild2(item.Id); if (t != null) { z.IsParent = true; childList.AddRange(t); } else { z.IsParent = false; } } } // 递归退出条件 if (childList.Count == 0) { return null; } return childList; }