如何使用Linq进行多级父子排序?

5
如果我有以下表结构,如何使用Linq进行多级父子排序?
预期的排序结果:
[表: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
3个回答

8

使用邻接表进行分层搜索/排序并不容易,特别是在Linq中。

我不会在此处编写一大块代码来完成此操作,而是将您转至已经完成此操作的其他人:

Linq AsHierarchy()扩展方法

这将把邻接表转换为实际的树形结构,然后可以轻松地按层次显示/搜索/排序。


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

只有在层次结构已按ID排序的情况下,此方法才有效,但这种情况不太可能发生。在根节点上放置[1]和[5],分别带有子节点[8]和[2];[2]的子节点将出现在[8]的子节点之前,这是错误的。 - Aaronaught
似乎将SectionS1放在列表的最末尾,ASummary放在倒数第二位。 - Mikael Svenson

0

我打赌

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

只需要这些,Linq会处理剩下的事情,你只需要指定LoadWith语句的状态。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接