You need to enable JavaScript to run this app. 递归按ID查找对象时如何返回包含所有父级名称的路径
优惠活动
大模型
产品
解决方案
定价
更多

递归按ID查找对象时如何返回包含所有父级名称的路径

调整思路

现有递归仅做目标匹配,没有在遍历过程中记录层级链路,核心调整方向是在递归逻辑中维护遍历路径信息,同时利用递归回溯机制自动修正路径,避免遍历失败分支的节点污染最终结果。

两种可落地的实现方案

方案1:递归返回布尔值自动拼路径(轻量,适合直接输出拼接字符串的场景)

不需要手动维护栈结构,利用递归的返回机制,从匹配到的最底层节点开始,逐层向上拼接父级名称,完全适配原有深度剪枝逻辑。

调整后的代码

// 新增:存储最终路径的字段,和原有selectedLocation字段的作用对齐
protected string selectedLocationPath;

protected bool TryBuildLocationPath(InventLocationViewModel currentNode, int targetId, int remainingDepth)
{
    if (remainingDepth < 0)
        return false;

    // 匹配到目标节点:保留原有selectedLocation赋值逻辑,初始化路径为当前节点名称
    if (currentNode.Id == targetId)
    {
        selectedLocation = currentNode;
        selectedLocationPath = currentNode.Name;
        return true;
    }

    // 遍历子节点,保留原有深度递减逻辑
    foreach (var child in currentNode.ChildInventLocations)
    {
        // 子分支找到目标后,把当前父节点名称拼在路径前面
        if (TryBuildLocationPath(child, targetId, remainingDepth - 1))
        {
            selectedLocationPath = $"{currentNode.Name}/{selectedLocationPath}";
            return true;
        }
    }

    // 当前分支无匹配,返回false继续回溯
    return false;
}

protected void SelectedLocation(RecursiveSelectObject args)
{
    // 原有逻辑保留,补充空引用判断
    currentLocation = locations.InventLocations.FirstOrDefault(e => e.Id == locationId.Value);
    if (currentLocation == null)
        return;

    // 替换原有FindPath调用
    bool isFound = TryBuildLocationPath(currentLocation, args.Id, args.Level);

    if (isFound)
    {
        // 可直接使用selectedLocation、selectedLocationPath完成后续业务逻辑
    }
}

方案2:维护路径栈(适合需要拿到完整节点对象列表的场景)

如果后续不光需要路径字符串,还要拿到路径上每个节点的ID、其他属性,就用栈结构记录遍历节点,遍历失败的分支自动弹出栈,保证最终栈内只有从根到目标的完整链路。

调整后的代码

// 存储路径上的所有节点对象
protected List<InventLocationViewModel> locationPathStack = new List<InventLocationViewModel>();
// 复用方案1里的selectedLocationPath字段
protected string selectedLocationPath;

protected void FindPathWithStack(InventLocationViewModel currentNode, int targetId, int remainingDepth)
{
    if (remainingDepth < 0)
        return;

    // 进入当前节点,先加入路径栈
    locationPathStack.Add(currentNode);

    // 匹配到目标:保留原有selectedLocation赋值逻辑,直接从栈生成路径字符串
    if (currentNode.Id == targetId)
    {
        selectedLocation = currentNode;
        selectedLocationPath = string.Join("/", locationPathStack.Select(node => node.Name));
        return;
    }

    // 遍历子节点
    foreach (var child in currentNode.ChildInventLocations)
    {
        FindPathWithStack(child, targetId, remainingDepth - 1);
        // 如果已经匹配到目标,直接终止后续遍历
        if (selectedLocation != null && selectedLocation.Id == targetId)
            return;
    }

    // 当前分支遍历完没找到,弹出当前节点回溯
    locationPathStack.RemoveAt(locationPathStack.Count - 1);
}

调用方式和原有逻辑兼容,只需要替换原来的FindPath方法即可,找到目标后可以直接通过locationPathStack拿到所有层级的节点ID、名称等信息。

注意事项
  • 原有深度剪枝逻辑(depth < 0 直接返回)在两种方案中都完全保留,不会改变原有遍历范围
  • 原有从根节点启动遍历的逻辑没有改动,只补充了路径生成的逻辑,和现有代码兼容性强
  • 建议补充根节点为空、子节点集合为空的边界判断,避免空引用异常

内容的提问来源于stack exchange,提问作者Povilas Dirse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.06 17:15:03