Return hierarchy from sql in lists in c# using linq

非 Y 不嫁゛ 提交于 2019-12-24 12:18:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!