【.Net】.Net中使用Linq递归查询数据

前言

在业务中经常会遇到递归算法, 比如需要根据上下级关系递归查找所有组织机构,并通过树形在前端展示

递归方法

  /// <summary>
        /// 使用递归方法
        /// </summary>
        /// <param name="treeNodes">所有数据(没有层级)</param>
        /// <param name="resps">通过递归最终形成层级数据</param>
        /// <param name="pID">父ID</param>
        /// <returns></returns>
        public static List<OrganizationModel> GetChildOrdList(List<OrganizationModel> treeNodes, List<OrganizationModel> resps, Guid pID)
        {
            resps = new List<OrganizationModel>();
            List<OrganizationModel> tempList = treeNodes.Where(c => c.ParentID == pID).ToList();
            if (tempList.Count == 0)
            {
                return null;
            }
            for (int i = 0; i < tempList.Count; i++)
            {
                OrganizationModel node = new OrganizationModel();
                node.ID = tempList[i].ID;
                node.OrgCode = tempList[i].OrgCode;
                node.ParentID = tempList[i].ParentID;
                node.OrgFullName = tempList[i].OrgFullName;
                node.OrgShortName = tempList[i].OrgShortName;
                node.OrgLabel = tempList[i].OrgLabel;
                node.OrgNaviName = tempList[i].OrgNaviName;
                node.OrgNaviUrl = tempList[i].OrgNaviUrl;
                node.OrgArea = tempList[i].OrgArea;
                node.Enabled = tempList[i].Enabled;
                node.OrderIndex = tempList[i].OrderIndex;
                node.CreateTime = tempList[i].CreateTime;
                node.LastUpdateTime = tempList[i].LastUpdateTime;
                node.ChildOrgCount = treeNodes.Where(c => c.ParentID == tempList[i].ID).Count();
                node.HasChild = node.ChildOrgCount > 0 ? true : false;
                node.ChildrenOrganization = GetChildOrdList(treeNodes, resps, node.ID);
                
                resps.Add(node);
            }

            return resps;
        }

 调用递归方法

//获取没有层级的所有数据
List<OrganizationModel> list = await query.ToListAsync(cancellationToken);
//调用递归方法
list = GetChildOrdList(list, new List<OrganizationModel>(), request.PagedQuery.FilterModel.ParentID);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一起来学吧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值