我在SQL中有两个表:
DOCUMENT
ID int
Description varchar(50)
DOCUMENTLINK
ParentID int
ChildID int
如何使用LINQ将这两个表形成的层次结构(仅使用两个级别)作为对象返回?
结构类似于:
Parent1
---------Child1
---------Child2
Parent2
---------Child3
Parent3
Parent4
---------Child2
---------Child3
Parent5
---------Child1
---------Child4
---------Child5
答案 0 :(得分:2)
LINQ回答:
var tree = from top in nodes
from middle in nodes
from bottom in nodes
where top.Id == middle.ParentId
&& middle.Id == bottom.Id
select new
{
Top = top,
Middle = middle,
Bottom = bottom
};
答案 1 :(得分:1)
SQL答案是:
SELECT *
FROM (Table1
INNER JOIN Table1 AS Table1_1 ON Table1.ParentID = Table1_1.ID)
INNER JOIN Table1 AS Table1_2 ON Table1_1.ParentID = Table1_2.ID;
注意,这只会显示包含所有级别的项目。要包含无子级父项,请将所有内连接更改为左外连接