实体结构:
public class Sys_Menu { public string MenuCode { get; set; } public string MenuDesc { get; set; } public string ParentCode { get; set; } }
/// <summary> /// 获取current所有子级 /// </summary> /// <param name="list"></param> /// <param name="current"></param> /// <returns></returns> public static List<Sys_Menu> GetChildren(List<Sys_Menu> list, Sys_Menu current) { var query = list.Where(x => x.ParentCode == current.MenuCode).ToList(); return query.Concat(query.SelectMany(t => GetChildren(list, t))).ToList(); } /// <summary> /// 获取current的所有父级 /// </summary> /// <param name="list"></param> /// <param name="current"></param> /// <returns></returns> public static List<Sys_Menu> GetParents(List<Sys_Menu> list, Sys_Menu current) { var query = list.Where(x => x.MenuCode == current.ParentCode).ToList(); return query.Concat(query.SelectMany(t => GetParents(list, t))).ToList(); }
测试代码:
Sys_Menu menu = new Sys_Menu { MenuCode = "01", MenuDesc = "根节点", ParentCode = null }; Sys_Menu menu1 = new Sys_Menu { MenuCode = "02", MenuDesc = "系统管理", ParentCode = "01" }; Sys_Menu menu2 = new Sys_Menu { MenuCode = "03", MenuDesc = "用户管理", ParentCode = "02" }; Sys_Menu menu3 = new Sys_Menu { MenuCode = "04", MenuDesc = "角色管理", ParentCode = "02" }; Sys_Menu menu4 = new Sys_Menu { MenuCode = "05", MenuDesc = "基础数据", ParentCode = "01" }; List<Sys_Menu> menuList = new List<Sys_Menu>(); menuList.Add(menu); menuList.Add(menu1); menuList.Add(menu2); menuList.Add(menu3); menuList.Add(menu4); Expression<Func<Sys_Menu, Sys_Menu, bool>> tt = (x, y) => x.MenuCode == y.ParentCode; List<Sys_Menu> parents = new List<Sys_Menu>(); TreeUtil.GetParents(menuList, menu3, "MenuCode","ParentCode", parents); List<Sys_Menu> children = new List<Sys_Menu>(); TreeUtil.GetChildren(menuList, menu1, "MenuCode", "ParentCode", children); var mm = GetChildren(menuList, menu); var mm1 = GetParents(menuList, menu3); Console.ReadKey();