是否可以在linq查询的结果集中使用select语句?

时间:2014-10-16 13:59:43

标签: c# sql linq lambda

我有如下查询:

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中有类似的东西吗?

2 个答案:

答案 0 :(得分:2)

这是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示例中,优化器知道如何将子查询转换为连接。

答案 1 :(得分:0)

使用'加入'方法: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代码段,请参阅this gist

相关问题