When is the LINQ query actually get executed?

…衆ロ難τιáo~ 提交于 2021-02-19 08:46:07

问题


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 ) ...

Questions are:

  • 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.)


回答1:


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

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.




回答2:


Generally speaking LINQ tries to be as lazy as possible. For example you'd expect it to look something like this behind the scenes:

foreach ( string name in query ) ...
//Roughly translates into
while (query.MoveNext())
{
    string name = query.Current;
    ...
}

Which only gets the results as it needs them, one by one. This 'lazy'/'streamed' thinking works through the whole query - Select calls OrderBy as needed, which calls Where as needed which calls the Collection as needed.

The one oddity is the 'OrderBy' which, for implementation reasons, might retrieve all the needed results before ordering them, then stream the result. This retrieval will occur when it's first called.




回答3:


The query doesn't execute before the foreach. Each iteration in your foreach loop will return one result from your query.

Never is there a fully materialized result set of data, so it can't be too large either.

A LINQ query defers execution. As you iterate it will 'slide' forward over your data applying the predicates and projections you specified.



来源:https://stackoverflow.com/questions/12118376/when-is-the-linq-query-actually-get-executed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!