嵌套“从"用扩展方法表示的 LINQ 查询 [英] Nested "from" LINQ query expressed with extension methods

查看:21
本文介绍了嵌套“从"用扩展方法表示的 LINQ 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用扩展方法语法编写此 LINQ 查询?

How can I write this LINQ query by using the extension method syntax?

var query = from a in sequenceA
            from b in sequenceB
            select ...; 

推荐答案

为了您以后的参考,此形式的所有问题都在 C# 规范的第 7.16 节中得到解答.

For your future reference, all questions of this form are answered by section 7.16 of the C# specification.

本段回答了您的具体问题:

Your specific question is answered by this paragraph:

带有第二个 from 子句后跟 select 子句的查询表达式

A query expression with a second from clause followed by a select clause

from x1 in e1
from x2 in e2
select v

被翻译成

( e1 ) . SelectMany( x1 => e2 , ( x1 , x2 ) => v )

<小时>

所以你的查询:


So your query:

var query = from a in sequenceA            
            from b in sequenceB
            select ...;  

var query =  ( sequenceA ) . SelectMany( a => sequenceB , ( a , b ) => ... )

(请注意,这当然假设..."是一个表达式,而不是一个后跟查询继续的表达式.)

(Note that of course this assumes that the "..." is an expression, and not, say, an expression followed by a query continuation.)

hdv 的回答指出

var query =  ( sequenceA ) . SelectMany( 
    a => ( sequenceB ) . Select( b => ... ) );

也将是一个逻辑上有效的翻译,尽管它不是我们实际执行的翻译.在 LINQ 实现的早期,这是我们选择的翻译.然而,当你堆积更多的 from 子句时,它会使 lambda 嵌套越来越深,这给编译器带来了巨大类型推断问题.这种转换选择会破坏编译器的性能,因此我们引入了透明标识符机制,为我们提供了一种更便宜的方式来表示深度嵌套作用域的接缝.

would also be a logically valid translation, though it is not the translation we actually perform. In the early days of LINQ implementation, this was the translation we chose. However, as you pile on more from clauses, it makes the lambdas nest more and more deeply, which then presents the compiler with an enormous problem in type inference. This choice of translation wrecks compiler performance, so we introduced the transparent identifier mechanism to give us a much cheaper way to represent the seamntics of deeply nested scopes.

如果您对这些主题感兴趣:

If these subjects interest you:

有关为什么深度嵌套的 lambda 表达式是编译器难以解决的问题的更多想法,请参阅:

For more thoughts on why deeply nested lambdas present a hard problem for the compiler to solve, see:

http://blogs.msdn.com/b/ericlippert/archive/2007/03/26/lambda-expressions-vs-anonymous-methods-part-four.aspx

http://blogs.msdn.com/b/ericlippert/archive/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five.aspx

有关透明标识符的更多信息,请参阅 Wes Dyer 的这篇博文,他在 C# 3.0 中实现了它们:

For more information about transparent identifiers, see this post from Wes Dyer, who implemented them in C# 3.0:

http://blogs.msdn.com/b/wesdyer/archive/2006/12/22/transparent-identifiers.aspx

以及我关于它们的系列文章:

And my series of articles about them:

http://ericlippert.com/2014/07/31/transparent-identifiers-part-one/

这篇关于嵌套“从"用扩展方法表示的 LINQ 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆