How to do multi-level parent-child sorting using Linq?

How can I do multi-level parent-child sorting 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 sorting result:

  TOP  
   AAAA  
     SectionA1  
     SectionA2  
     Asummary  
   Ssss  
     SectionS1  
   DDDD  
+4
source share
3 answers

Performing hierarchical search / sorting using the adjacency list is not easy, especially in Linq.

Instead of writing a large block of code here, I am sending you to someone else who has already done this:

Linq AsHierarchy () Extension Method

This converts the adjacency list into an actual tree structure, which is then easily displayed / searched / sorted hierarchically.

+7
source

I think it will be done. It is not verified, so let me know:

from section in db.Sections group section by section.ParentSectionId into childGroup orderby childGroup.Key from childSection in childGroup.OrderBy(child => child.Seq) select childSection 
0
source

I bet

 from section in db.Sections where section.sec=0 orderby section.Name 

will be enough, and Linq will do the rest, only you need to indicate the state of the LoadWith statement

0
source

Source: https://habr.com/ru/post/1305380/


All Articles