Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

c# - Finding a path of recursion

Hello everyone I have a small problem and I feel a little bit stuck. I manage to get the object that I want, but I don't know how to return the path to that object (how I found it). My code looks like this at the moment:

P.S what I mean by path: every single item has it's name and id. I manage to find an object with id (which I give when call for recursion) and when I find it, I need to create string and add all of it's parents names to it and return it.

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)
        {

        }
    }

enter image description here

question from:https://stackoverflow.com/questions/65906631/finding-a-path-of-recursion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You know what you want to keep on the way out:

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...