简体   繁体   English

在LINQ中创建两级层次结构

[英]Creating a two-level hierarchy in LINQ

I have two tables in SQL: 我在SQL中有两个表:

DOCUMENT
ID int
Description varchar(50)

DOCUMENTLINK
ParentID int
ChildID int

How do I return the hierarchy (only two levels are used) formed by these two tables as an object using LINQ? 如何使用LINQ将这两个表形成的层次结构(仅使用两个级别)作为对象返回?

The structure would be something like: 结构如下:

Parent1  
---------Child1  
---------Child2  
Parent2  
---------Child3  
Parent3  
Parent4  
---------Child2  
---------Child3  
Parent5  
---------Child1  
---------Child4
---------Child5

LINQ answer: 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
           };

The SQL answer is: 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;

Note, this will only show items that have all levels. 请注意,这只会显示具有所有级别的项目。 To get childless parents included, change all the inner joins to left outer joins 要包括没有子女的父母,请将所有内部联接更改为左侧外部联接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM