Deferred and immediate executions in LINQ


We will create a simple list of strings and query the list through LINQ.

static void Main(string[] args)
{

    List<String> strlist = new List<string>() { "string 1", "string 2", "string 3", "string 4" };
    var q = from strings in strlist
    select strings;
    foreach (string str in q)
    {
        Console.WriteLine(str);
    }
    Console.ReadKey();
}

The output of the above program is

Deferred in liinq

Now refer to the image below

Deferred execution in liinq

How can we check that what we have mentioned in the above image is correct ? Let us add one more string AFTER the LINQ query.

immediate executions in LINQ

So what's the output now ?

Untitled-30.gif

When we added "string 5" after the query, it was still considered in the FOREACH loop. So we can say that with foreach loop, the query was executed only when the values were required.

We can also make the query execute where it was defined by using. ToList() or ToArray() on the LINQ query which will cause the immediate execution of the LINQ query.

immediate execution of the LINQ

And the output is

immediate executions

The query was executed before the foreach loop at the query definition itself because of the use to ToArray() method.

The immediate execution in a LINQ query also takes place if the query is returning single value, like the COUNT for instance

    int count = (from strings in strlist
    select strings).Count();

This query will get executed immediately and assign the count to the variable.


Similar Articles