首页 > 解决方案 > 寻找递归路径

问题描述

大家好,我有一个小问题,我感觉有点卡住了。我设法获得了我想要的对象,但我不知道如何返回该对象的路径(我是如何找到它的)。我的代码现在看起来像这样:

PS我的意思是路径:每个项目都有它的名称和ID。我设法找到一个带有 id 的对象(我在调用递归时给出),当我找到它时,我需要创建字符串并将它的所有父名称添加到它并返回它。

protected void FindPath(int depth, int id, InventLocationViewModel currentLocation)
    {
        if (depth < 0)
            return;

        if (currentLocation.Id == id)
        {
            selectedLocation = currentLocation;
            return;
        }

        foreach (var child in currentLocation.ChildInventLocations)
        {
            FindPath(depth - 1, id, child);
        }
    }

    protected void SelectedLocation(RecursiveSelectObject args)
    {
        currentLocation = locations.InventLocations.FirstOrDefault(e => e.Id == locationId.Value);

        FindPath(args.Level, args.Id, currentLocation);

        if (selectedLocation.Id == args.Id)
        {

        }
    }

在此处输入图像描述

标签: c#recursion

解决方案


您知道在退出过程中要保留的内容:

protected List<InventLocationViewModel> FindPath(int id, InventLocationViewModel currentLocation)
{
    if (currentLocation.Id == id)
    {
        return new List<InventLocationViewModel> {currentLocation};
    }

    foreach (var child in currentLocation.ChildInventLocations)
    {
        var result = FindPath(id, child);
        if (result != null)
        {
            result.Add(currentLocation);
            return result;
        }
    }
    return null;
}

推荐阅读