父子关系的实体集合转为树结构

需求是 :把有父子关系的实体集合转为树结构的的集合,本以为可以使用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;
}

寻找更好的实现方法,有答案的请不惜共享!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值