使用linq从C#中的列表中的SQL返回层次结构 [英] Return hierarchy from sql in lists in c# using linq
本文介绍了使用linq从C#中的列表中的SQL返回层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在sql中有一个表,该表具有三列(ID,名称,ParentID),每列都有很多记录.现在,我想要的是从ParrentId中获取所有的学习成果,并将其包含在三个视图中.
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.
可以通过一些不错的LINQ解决方案来解决吗?
Is that can be solved with some nice LINQ solution?
我之前尝试过的方法是使用其中一个是孩子的List-s集,但是出现问题的原因是某些孩子列表也可以有更多孩子.
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.
我需要使用linq代码:
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});
但是在实际示例中,当然不会只有3个子变量.
but of course in real example it wouldnt be just 3 child var-s.
感谢任何帮助和建议!
推荐答案
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);
}
}
这篇关于使用linq从C#中的列表中的SQL返回层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文