在LINQ中创建两级层次结构

时间:2013-09-09 11:45:09

标签: sql linq linq-to-sql

我在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

2 个答案:

答案 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;

注意,这只会显示包含所有级别的项目。要包含无子级父项,请将所有内连接更改为左外连接