【发布时间】:2014-10-16 13:59:43
【问题描述】:
我有如下查询:
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 中是否有类似的东西?
【问题讨论】:
我有如下查询:
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 中是否有类似的东西?
【问题讨论】:
这是对 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 to Objects 查询,它具有二次性能。在 T-SQL 示例中,优化器知道如何将子查询转换为连接。
【讨论】:
使用“加入”方法: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 sn-p,请参阅 this gist。
【讨论】: