前言
在业务中经常会遇到递归算法, 比如需要根据上下级关系递归查找所有组织机构,并通过树形在前端展示
递归方法
/// <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);