1

我有一个本身具有树结构的表。

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 做到这一点?

4

3 回答 3

1

如果您能够更改表结构以添加额外的字段,那么我过去使用的一种方法是拥有一个“路径”字段,其中包含一个逗号分隔的 ID 列表。

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

然后您可以使用 LIKE(或 Linq 中的 StartsWith)基于 Path 字段进行查询

在您的问题中,您说您想获得 { 1, 5, 6, 7, 10, 11, 12 },但如果我没看错的话,这些 ID 是两个不同子树的一部分。

得到“x”和它所有的孩子......

where Path = "1" || Path.StartsWith("1,")

为了得到x的孩子......

where Path.StartsWith("1,")
于 2009-03-23T09:03:18.867 回答
0

您需要使用表本身在 Linq 中执行内部联接,如下所示:

from root in TableName 
join subnodes in TableName on root.Id equals subnodes.ParentId
select new { Name }

这将检索父 id 与 Id 匹配的所有记录,并将同一个表重命名为子节点

谢谢

于 2011-10-18T10:40:37.743 回答
0
    /// <summary>
    /// Allows to recursively select descendants as plain collection
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    /// <param name="DescendBy"></param>
    /// <returns></returns>

    public static IEnumerable<T> Descendants<T>(
        this IEnumerable<T> source, Func<T, IEnumerable<T>> DescendBy)
    {
        foreach (T value in source)
        {
            yield return value;

            foreach (var child in DescendBy(value).Descendants(DescendBy))
            {
                yield return child;
            }
        }
    }

用法:node.children.Descendants(node=>node.children);

于 2009-04-27T08:58:01.773 回答