如何获得通过LINQ树状结构表中的数据? [英] How to get a tree structured table data by linq?
问题描述
我有这本身就具有树形结构的表。
I have a table which has a tree structure in itself.
Id ParentId Name
----------------
1 null x
2 null y
3 null z
4 null t
5 1 xx
6 1 xy
7 1 xz
8 2 yx
9 2 yy
10 9 yyx
11 10 yyxx
12 11 yyxxx
我想找回一个根节点下的整个子树。当我的根节点为x我想要得到的节点集合{1,5,6,7,10,11,12}的。我怎样才能做到这一点的LINQ?
I want to retrieve the whole sub-tree under a root node. When my root node is "x" I want to get the set of nodes {1, 5, 6, 7, 10, 11, 12}. How can I do that by linq?
推荐答案
如果你能够改变的表结构中添加额外的字段,再一个方法我已经在过去使用是有一个路径字段中,其中包含逗号分隔的ID列表。
If you're able the change the table structure to add extra fields, then one approach I have used in the past is to have a "Path" field, which holds a comma separated list of IDs.
ID ParentID Name Path
-- -------- ---- ----
1 null x 1
2 null y 2
3 null z 3
4 null t 4
5 1 xx 1,5
6 1 xy 1,6
7 1 xz 1,7
8 2 yx 2,8
9 2 yy 2,9
10 9 yyx 2,9,10
11 10 yyxx 2,9,10,11
12 11 yyxxx 2,9,10,11,12
然后你可以使用像(或StartsWith中的LINQ)查询基于路径字段
Then you can query based on the Path field using LIKE (or StartsWith in Linq)
在你的问题你说你想要得到{1,5,6,7,10,11,12},但这些ID是两个不同的子树的一部分,如果我没有看错!
In your question you say you want to get { 1, 5, 6, 7, 10, 11, 12 }, but those IDs are part of two different sub-trees, if I've read it right.
要获得x和所有它的孩子......
To get "x" and all it's children ...
where Path = "1" || Path.StartsWith("1,")
要只得到X的孩子......
To just get x's children ...
where Path.StartsWith("1,")
这篇关于如何获得通过LINQ树状结构表中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!