.net 使用LINQ选择分层数据?

.net 使用LINQ选择分层数据?,.net,sql-server,linq,linq-to-sql,hierarchical-data,.net,Sql Server,Linq,Linq To Sql,Hierarchical Data,我在SQL Server中有一个表,其结构如下: id Name Parent -- ---- ------ 1 foo null 2 bar 1 3 oof null 4 rab 3 . . . Parent Child ------ ----- foo bar oof rab 我需要将两个关联行中的数据作为.NET数据表中的一行来获取。我想要的数据表如下所示: id Name Parent -- ---- ------

我在SQL Server中有一个表,其结构如下:

id  Name  Parent
--  ----  ------
1   foo   null
2   bar   1
3   oof   null
4   rab   3
.
.
.
Parent  Child
------  -----
foo     bar
oof     rab
我需要将两个关联行中的数据作为.NET数据表中的一行来获取。我想要的数据表如下所示:

id  Name  Parent
--  ----  ------
1   foo   null
2   bar   1
3   oof   null
4   rab   3
.
.
.
Parent  Child
------  -----
foo     bar
oof     rab
我可以通过下面的查询来完成这项工作:

with temp as
(
  SELECT 1 id,'foo' name, null parent
  UNION
  select 2,'bar', 1
  UNION
  SELECT 3,'oof', null
  UNION
  select 4,'rab', 3
)

SELECT t1.name parent, t2.name child
FROM temp t1
INNER JOIN temp t2
ON t1.id = t2.parent
但我很好奇,是否有一种简单的方法可以使用LINQ实现这一点?(我们的商店使用LINQ进行大多数数据库访问)


选择只会将结果投影回您。因此,只需在本地列表中选择您需要的内容,或者使用一点语法,您就可以使用匿名投影将所有级别的数据封装在一起,并在此基础上进行过滤。ToList()返回给您。

我更喜欢将连接保留为连接

var result = source.Select(child => new { 
 Child = child, 
 Parent = source.SingleOrDefault(parent => parent.ID == child.Parent)
});
var result = from t1 in table
join t2 in table on t1.id = t2.parent
select new { parent = t1.name, child = t2.name }

这里的LINQ语句是禁止操作的…为什么不使用LINQ连接呢?