Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a multi level parent-child sort using Linq?

How can I do a multi-level parent-child sort using Linq if I have a table structure like the one below:

[Table: Sections]  
Id   Seq   Name        ParentSectionId  
1    1     TOP         NULL  
2    1     AAAA        1  
3    2     SSSS        1
4    3     DDDD        1  
5    1     SectionA1   2
6    2     SectionA2   2  
7    1     SectionS1   3  
8    3     ASummary    2  

Expected sort result:

TOP  
  AAAA  
    SectionA1  
    SectionA2  
    ASummary  
  SSSS  
    SectionS1  
  DDDD  
like image 840
Tenacious T Avatar asked Mar 28 '10 20:03

Tenacious T


1 Answers

Performing a hierarchical search/sort with an adjacency list is not an easy thing to do, especially in Linq.

Rather than write a big block of code here to do this, I will refer you to somebody else who has already done it:

Linq AsHierarchy() Extension Method

This will convert the adjacency list into an actual tree structure, which is then easy to display/search/sort in a hierarchical fashion.

like image 53
Aaronaught Avatar answered Oct 28 '22 09:10

Aaronaught