第一种方法好些
第二种方法如果中间断开就会成为一级
private static List<Menu> MenuTree() { var menu1 = new Menu { Id = 1, ParentId = 0, Name = "aaa" }; var menu2 = new Menu { Id = 2, ParentId = 0, Name = "bbb" }; var menu3 = new Menu { Id = 3, ParentId = 0, Name = "ccc" }; var menu4 = new Menu { Id = 4, ParentId = 1, Name = "ddd" }; var menu5 = new Menu { Id = 5, ParentId = 2, Name = "eee" }; var menu6 = new Menu { Id = 6, ParentId = 4, Name = "fff" }; var menu7 = new Menu { Id = 7, ParentId = 5, Name = "ggg" }; var menu8 = new Menu { Id = 8, ParentId = 6, Name = "hhh" }; var menuAll = new List<Menu> { menu1, menu2, menu3, menu4, menu5, menu6, menu7, menu8 }; var menuList = new List<Menu> { menu1, menu2, menu3, menu4, menu5, menu7, menu8 }; //第一种方法 while (true) { var idList = menuList.Select(x => x.Id).ToList(); idList.AddRange(menuList.Select(x => x.ParentId).ToList()); idList = idList.Distinct().ToList(); var menus = menuAll.Where(x => idList.Contains(x.Id)).ToList(); if (menus.Count != menuList.Count) { menuList = menus; continue; } break; } //第二种方法 var ret = new List<Menu>(); foreach (var menu in menuList) { var model = menuList.FirstOrDefault(x => x.Id == menu.ParentId); if (model == null) { ret.Add(menu); continue; } model.Children.Add(menu); } return ret; }