最近工作中涉及到菜單,各種遞歸.總結了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; }