asp .net core 构建树形结构

 public class BuildTreeExtension
    {
        public List<T> GetChildList<T>(string parentId, List<T> sourceList, string idFieldName, string sjIdFieldName, string childFieldName)
        {
            List<T> list = new List<T>();
            if (sourceList != null && sourceList.Count > 0)
            {
                var tempList = new List<T>();
                //找到所有子级节点
                foreach (var item in sourceList)
                {
                    Type t = item.GetType();
                    object curParentID = t.GetProperty(sjIdFieldName).GetValue(item, null);
                    if (curParentID != null && curParentID.ToString() == parentId)
                    {
                        tempList.Add(item);
                    }
                }
                if (tempList != null && tempList.Count > 0)
                {
                    foreach (var item in tempList)
                    {
                        //获取当前子节点的ID值

 						Type t = item.GetType();
                        object curID = t.GetProperty(idFieldName).GetValue(item, null);
                        List<T> itemList = new List<T>();
                        if (curID != null && !string.IsNullOrEmpty(curID.ToString()))
                        {
                            //获取子节点的子节点集合
                            itemList = GetChildList(curID.ToString(), sourceList, idFieldName, sjIdFieldName, childFieldName);
                        }
                        //赋值子节点集合
                        if (itemList != null && itemList.Count > 0)
                        {
                            t.GetProperty(childFieldName)?.SetValue(item, itemList, null);
                        }
                        list.Add(item);
                    }
                }
            }
            return list;
        }
    }
    ```
调用方式

```csharp
			 //最顶级数据
            var parentList = source.FindAll(x => string.IsNullOrWhiteSpace(x.sj_id));
            var treeExtension = new BuildTreeExtension();
            var result = new List<BsptTreeResDto>();
            parentList?.ForEach(x =>
            {
                //构建下级
                x.child = treeExtension.GetChildList(x.id, source, nameof(x.id), nameof(x.sj_id), nameof(x.child));
                result.Add(x);
            });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值