需求是 :把有父子关系的实体集合转为树结构的的集合,本以为可以使用entity framework中的include可以实现,测试结果是失败的,只能用递归了,写这篇博客主要是希望看到的人能给出更好的更简单的办法。
实体如下:
public class PMENU
{
[Display(Name = "编号")]
public string BH { get; set; }
[Display(Name = "上级编号")]
public string FBH { get; set; }
public List<PMENU> list { get; set; }
}
数据如下:
List<PMENU> list=new List<PMENU>{
new PMENU{BH=1,FBH=null},//父元素
new PMENU{BH=2,FBH=1},//子元素
new PMENU{BH=3,FBH=1}//子元素
};
希望得到的新集合是:
List<PMENU> list=new List<PMENU>{
new PMENU{BH=1,FBH=null},//父元素
list=new List<PMENU>{
new PMENU{BH=2,FBH=1},//子元素
new PMENU{BH=3,FBH=1}//子元素
}
};
实现方法:
//递归方法:根据父节点获取子节点
public static List<PMENU> GetListTree(List<PMENU> list, string id)
{
var child = list.Where(o => o.FBH == id).ToList();
if (child.Count > 0)
{
foreach (var item in child)
{
item.list = GetListTree(list, item.BH);
}
return child;
}
return null;
}
寻找更好的实现方法,有答案的请不惜共享!!