smwikipedia
smwikipedia

Reputation: 64453

When is the LINQ query actually get executed?

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:

Upvotes: 1

Views: 333

Answers (3)

NPSF3000
NPSF3000

Reputation: 2451

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.

Upvotes: 3

user45886
user45886

Reputation:

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.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839254

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.

Upvotes: 5

Related Questions