2010-03-28 63 views
4

我该怎么办了多层次的父子排序使用LINQ如果我有类似下面的表结构:如何使用Linq进行多级亲子排序?

 
[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 

预期的排序结果:

 
TOP 
    AAAA 
    SectionA1 
    SectionA2 
    ASummary 
    SSSS 
    SectionS1 
    DDDD 

回答

7

执行分层搜索/排序邻接列表并不是一件容易的事情,特别是在Linq中。

而不是写在这里的代码大块要做到这一点,我会向您推荐别人谁已经做到了:

Linq AsHierarchy() Extension Method

这将邻接表转换成实际的树形结构,然后便于以分层方式显示/搜索/排序。

0

我认为这样做。这是未经测试,所以让我知道:

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

这只会工作如果层次结构已按排序顺序排序,则不太可能。图片[1]和[5]在根,与各自的孩子[8]和[2]; [2]的孩子会出现在[8]的孩子面前,这是错误的。 – Aaronaught 2010-03-28 20:43:27

+0

似乎将SectionS1放在列表的最后,ASummary倒数第二。 – 2010-03-28 20:47:33

0

我敢打赌

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

就足以和LINQ将完成剩下的 只有你有指定状态LoadWith声明