【问题标题】:is it possible to have a select statement in the resultset of a linq query?是否可以在 linq 查询的结果集中有一个 select 语句?
【发布时间】: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 中是否有类似的东西?

【问题讨论】:

    标签: c# sql linq lambda


    【解决方案1】:

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

    【讨论】:

    • 我明白了,谢谢你的解释。这说明了很多。接受。
    【解决方案2】:

    使用“加入”方法: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

    【讨论】:

    • 正如 OP 所写:“我知道我可以在 linq 中执行连接,但在 linq 中是否有类似的东西?”
    • 我不明白反对意见。答案在 linq 语法中显示了类似的内容。你想用 .Method 风格写吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    相关资源
    最近更新 更多