层次问题->用Linq Join替换递归? [英] Hierarchy Problem -> Replace Recursion with Linq Join?

查看:64
本文介绍了层次问题->用Linq Join替换递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自我参照表,该表的ID为ParentID(可为空).

I have a self referential table, which has ID, ParentID (nullable).

因此,该表包含许多节点,每个节点都可以是层次结构中的根(父级为null)或层次结构的任何级别(父级存在于表中的其他位置).

So, the table contains many nodes, each node could be the root in the hierarchy (parent is null), or any level of the hierarchy (parent exists elsewhere in the table).

给定一个任意的起始节点,是否存在一个优雅的linq查询,该查询将从该节点返回层次结构的所有子级?

Given an arbitrary starting node, is there an elegant linq query that will return all children of the hierarchy from that node?

谢谢.

推荐答案

如果您要选择节点的所有直接子代,则可以执行如下所示的简单查询:

If you want to select all direct children of a node, a simple query like the following should do the job:

from item in table
where item.ID == parentID;
select item

如果要选择节点的所有后代,则对于LINQ来说是不可能的,因为它需要递归或LINQ(和SQL)不提供的堆栈.

If you want to select all descendants of a node, this is not possible with LINQ, because it requires recursion or a stack which LINQ (and SQL) doesn't provide.

另请参阅:

  • StackOverflow: LINQ to SQL for self-referencing tables?
  • CodeProject: T-SQL - How to get all descendants of a given element in a hierarchical table
  • StackOverflow: Expressing recursion in LINQ

这篇关于层次问题->用Linq Join替换递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆