gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:37:19 24 4
gpt4 key购买 nike

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

id  Name  Parent
-- ---- ------
1 foo null
2 bar 1
3 oof null
4 rab 3
.
.
.

我需要从两个关联的行中获取数据作为 .NET DataTable 中的一行。我想要的 DataTable 看起来像这样:

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 进行大部分数据库访问)

最佳答案

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

var result = from t1 in table
join t2 in table on t1.id = t2.parent
select new { parent = t1.name, child = t2.name }

关于.net - 使用 LINQ 选择分层数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4073770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com