N
N
Ness2021-12-24 14:44:18
Database
Ness, 2021-12-24 14:44:18

How to recursively get all parents of a child?

There are all locations of the type (let's say 100 pieces, these are locations for the TreeView):
Id, Name, ParentId
1 Root Null
2 ​​Semi-root 1
3 Semi-root 2

And there is data in which we received only those locations that correspond to our values ​​from another request:
Id, Name, ParentId
22 Location1 12
36 Location38 21

It is necessary to make 1 object from these two selections in the form

public class TreeViewNode {
  public Guid Id {get; set;}
  public string Name {get; set;}
  public Guid ParentId {get; set;}
}


var locations = new List(); - and here, specifically, our selection from the second request in which we received specific locations and whose parents we pulled out by parent ID in the selection of all locations.

Can you tell me how to get these values?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vlad, 2022-01-03
@Taifunov

Recursively. As I understand it, you have a list of TreeViewNode's, so to find all the parents, you need a function that will take one TreeViewNode instance, and return a list or an array of Guid or TreeViewNode (depending on the situation).
something like this pseudocode

public List<TreeViewNode> nodes = ...; 
public List<Guid> GetAllParentsId(Guid Id)
{
        List<Guid> response = new List<Guid>();
        TreeViewNode current = nodes.FirstOrDefault(n => n.Id == Id);
        if(current is null)
        {
                return response;
        }
        //response.Add(current);
        var mynodes = GetAllParentsId(current.Id);
        if(mynodes.Count == 0)
        {
                return response;
        }
        response.AddRange(mynodes);
        return response;
}

R
Roman, 2021-12-24
@yarosroman

recursion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question