Web
Analytics
Deferred execution in LINQ | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

The Most of LINQ query operators do not execute immediately,  their execution is deferred to a later time in the program execution.

It  means that the query does not execute when it is created, but when it is used or enumerated.

Mean of Deferred execution is that the inputs can be modified after the query is constructed so that output would be changed.

//Defered Execution of LINQ Query

int[] Original_inputsequence = { 1, 2, 3, 4, 5, 6 };

 

// Query Construction

IEnumerable<int> InputSequence_Condition = Original_inputsequence.Where(m => m > 3);

 

//Modify Input

Original_inputsequence[0]=100;

 

//Loop through origional Input Sequence

foreach(var outpunumber in InputSequence_Condition)

{

Console.WriteLine(outpunumber);

 

}

Console.ReadLine();

In given example Query will not executed until foreach is not implemented.

 

Note : Some operators who return Scalar result may cause immediate execution i.e min, max, count.

conversion operators that also cause immediate query execution are ToList, ToArray, ToLookup, and ToDictionary.

Example : In following example if I make changes like

 

IEnumerable<int> numbersGreaterThanTwoQuery = fibonacci.Where(x => x > 2) .ToArray();

Download Source Code