是否可以在linq查询的结果集中包含select语句

本文关键字:集中 结果 包含 select 语句 查询 linq 是否 | 更新日期: 2023-09-27 18:26:42

我有一个如下的查询:

select column_a, (select column_a from table_b where b.column_c = a.column_c) column_b
from table_a a where a.test = 1 order by a.number

我知道我可以在linq中执行联接,但在linq里有类似的东西吗?

是否可以在linq查询的结果集中包含select语句

这是SQL语句的直接翻译:

from a in table_a
where a.test == 1
orderby a.number
let column_b = (from b in table_b where b.column_c == a.column_c select b.column_a).SingleOrDefault()
select new { a.column_a, column_b }

请记住,这是一个嵌套循环,因此如果它是一个简单的LINQ到对象查询,那么它具有二次型性能。在T-SQL示例中,优化器知道如何将子查询转换为联接。

使用"Join"方法:http://msdn.microsoft.com/en-us/library/bb311040.aspx

在声明性语法中:

from item_a in table_a
join item_b in table_b on item_a.column_c equals item_b.column_c
where item_a.test == 1
orderby item_a.number
select new {column_a = item_a.column_a, column_b = item_b.column_a};

在方法语法中:

table_a.Where (item_a => item_a.test == 1)
  .Join(table_b,
    (item_a) => item_a.column_c,
    (item_b) => item_b.column_c,
    (item_a, item_b) => new { column_a = item_a.column_a, column_b = item_b.column_a });

请参阅此要点以获取可运行的LinqPad片段。