Deferred Execution

Query
public void Linq99()
{
// Sequence operators form first-class queries that
// are not executed until you enumerate over them.

int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

int i = 0;
var q =
from n in numbers
select ++i;

// Note, the local variable 'i' is not incremented
// until each element is evaluated (as a side-effect):
foreach (var v in q)
{
Console.WriteLine("v = {0}, i = {1}", v, i);
}
}
Lambda Expression
public void Linq99()
{

// Queries are not executed until you enumerate over them.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

int i = 0;
var simpleQuery = numbers.Select(num => ++i);

// The local variable 'i' is not incremented
// until the query is executed in the foreach loop.
Console.WriteLine("The current value of i is {0}", i); //i is still zero

foreach (var item in simpleQuery)
{
Console.WriteLine("v = {0}, i = {1}", item, i); // now i is incremented
}
}
Output
v = 1, i = 1
v = 2, i = 2
v = 3, i = 3
v = 4, i = 4
v = 5, i = 5
v = 6, i = 6
v = 7, i = 7
v = 8, i = 8
v = 9, i = 9
v = 10, i = 10
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +