【问题标题】:Loop hierarchy to root循环层次结构到根
【发布时间】:2013-01-29 08:54:59
【问题描述】:

我需要将层次结构向下循环到根。 这是我的表格列

  1. 身份证
  2. 父母身份
  3. 说明

我想你理解这个问题。 ParentId 为 NULL 的项是根。

例子

  • Id=1 ParentId=NULL 描述=Root
  • Id=2 ParentId=1 Description=Id1 的子项

这可以使用 linq 完成吗?或者使用 sql 查询更好。

【问题讨论】:

  • 您是说要返回特定项目的整个层次结构吗?

标签: c# linq sql-server-2008


【解决方案1】:

在 Sql Server 上这样的东西可能是解决方案:
4 示例如果我们想递归查找 Child1 的根,我们可以使用

WITH n(ID, Description) AS 
   (SELECT ID, Description
    FROM yourTable
    WHERE Description = 'Child1'
        UNION ALL
    SELECT nplus1.ID, nplus1.Description
    FROM youTable as nplus1, n
    WHERE n.ID = nplus1.ParentID)
SELECT name FROM n

看看MSDN 4 WITH关键字

Oracle 服务器上的相同解决方案将使用

SELECT Description 
  FROM yourTable
  START WITH name = 'Child1'
  CONNECT BY PRIOR ID = ParentID

【讨论】:

    【解决方案2】:

    如果可以更改(反转)您的树结构以使节点包含其子节点而不是引用其父节点,如下所示:

        class Node
        {
            public Guid Id { get; set; }
            public IEnumerable<Node> Children { get; set; }
            public string Description { get; set; }
        }
    

    然后很容易将树“展平”为具有如下扩展名的 IEnumerable:

        public static IEnumerable<T> FlattenedTree<T>(this T node, Func<T, IEnumerable<T>> getter)
        {
            yield return node;
            var children = getter(node);
            if(children != null)
            {
                foreach (T child in children)
                {
                    foreach (T relative in FlattenedTree(child, getter))
                    {
                        yield return relative;
                    }
                }
            }
        }
    

    你可以像这样在 linq 中使用你的树:

        var descriptions = MyTreeStructure.FlattenedTree(x => x.Children).Select(x => x.Description);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      相关资源
      最近更新 更多