[英]Creating a two-level hierarchy in LINQ
我在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
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
};
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;
請注意,這只會顯示具有所有級別的項目。 要包括沒有子女的父母,請將所有內部聯接更改為左側外部聯接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.