问题
I have table in sql which have three columns (ID, Name, ParentID) and each columns have many records. Now what i want is to get all hiearachy from ParrentId, to include it in three view.
Is that can be solved with some nice LINQ solution?
What i try before is to use set of List-s which one of those is child, but problem occur cause some child list can also have more childs under.
I need this with linq code:
List<Menu> hList = new List<Menu>();
var m1 = new Menu();
var m2 = new Menu();
var m3 = new Menu();
hList.AddRange(new List<Menu>() { m1, m2, m3});
but of course in real example it wouldnt be just 3 child var-s.
Thnx for any help and suggestion!
回答1:
public void FillMenu(EntityCollection menuList, List<Menu> hList, int? parentMenuId)
{
var g = from m in menuList
where ((MenuEntity)m).ParentMenuId == parentMenuId
select (MenuEntity)m;
foreach (MenuEntity menu in g)
{
var newMenu = new Menu();
newMenu.Id = menu.Id;
newMenu.Name = menu.Name;
newMenu.ChildMenu = new List<Menu>();
FillMenu(menuList, newMenu.ChildMenu, newMenu.Id);
hList.Add(newMenu);
}
}
来源:https://stackoverflow.com/questions/19148489/return-hierarchy-from-sql-in-lists-in-c-sharp-using-linq