As a result of the SQL query, I get the following data:

enter image description here

If PAR_Id = 0 , this is the root node. The result of the query is about 10,000 entries.

What is the optimal data structure to choose for building such a tree? Maybe someone will contribute to the construction of this tree, I will be immensely grateful.

UPD

I would like to get this structure: Tree

    2 answers 2

    The best option is the adjacency list, you need to google in this direction. In short, you need something like this:

     int n = 10000; // колчество записей List<List<int>> a = new List<List<int>>(n); foreach ( /* перебрать все записи */) { // parent_id - id родителя // child_id - id ребёнка a[parent_id].Add(child_id); a[child_id].Add(parent_id); } 

    Here a [i] is the list of those vertices that are adjacent to vertex i. But it is necessary to decide whether the graph is oriented or not. If the graph is oriented, then it is necessary to add only the edges from the parent to the descendant, or only from the descendant to the parent (depending on what then to do with this graph). If the graph is undirected, then both edges must be added

    The adjacency matrix is ​​not suitable due to the fact that you need an array of size 10 ^ 8

    • I think this solution will not work. I will deliver the constructed tree to the web-client in the form of Json and, on the basis of this Json, the menu will be built on the client. - romka.pm

    If you correctly sort the data in the request, you can not change anything and then build a tree in one pass.

      PAR_ID CHI_ID CHI_NOM
     0 1 G1
     1 2 G1-1
     2 3 G1-1-1
     2 4 G1-1-2
     1 5 G1-2
     0 6 G2
    

    Here is a good article about storing hierarchical structures in a database.

    • expensive operation, query execution time increased significantly. - romka.pm