何时真正执行LINQ查询? [英] When is the LINQ query actually get executed?

查看:61
本文介绍了何时真正执行LINQ查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下LINQ查询:

Suppose we have the following LINQ query:

var query =
    from    c in Customers
    where   c.Country == "Italy"
    orderby c.Name
    select  new { c.Name, c.City };

编译器将像这样转换它:

Compiler will convert it like this:

IEnumerable<Customer> query =
        Customers
        .Where( c => c.Country == "Italy" );
        .OrderBy( c => c.Name )
        .Select( c => new { c.Name, c.City } );

然后我会像这样使用查询:

Then I coud use the query like this:

foreach ( var name_city_pair in query ) ...

问题是:

  • 似乎已经查询了由查询指定的数据当我使用foreach循环时.那么,什么时候执行此查询操作?当我定义 IEnumerable< Customer> 的LINQ查询对象时是?

  • It seems the data specified by the query is already queried out when I use the foreach loop. So when is this query action take place? Is it when I define the LINQ query object of IEnumerable<Customer> ?

如果数据量太大,是否有任何后期查询机制?(我不确定用正确的词来形容这一点,但是我希望你能得到我.)

If the data number is too large, is there any late query mechanism? (I am not sure about the right word to describe this, but I hope you get me.)

推荐答案

LINQ在可能的情况下使用延迟执行.在您的示例中,仅当您遍历结果时才执行查询.

LINQ uses deferred execution where possible. In your example the query is only executed when you iterate over the results.

To 开头的方法(例如 ToList )使查询立即执行.另外,某些返回单个值的方法(例如 Count )会使查询立即执行.

The methods that start with To (such as ToList) cause the query to be executed immediately. Also some methods that return a single value such as Count cause the query to be executed immediately.

这篇关于何时真正执行LINQ查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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