Deferred Query Execution

Posted by Bhaskara under LINQ category on | Points: 40 | Views : 3483
In a query that returns a sequence of values, the query variable itself never holds the query results and only stores the query commands. Execution of the query is deferred until the query variable is iterated over in a foreach or For Each loop. This is known as deferred execution; that is, query execution occurs some time after the query is constructed. This means that you can execute a query as frequently as you want to. This is useful when, for example, you have a database that is being updated by other applications. In your application, you can create a query to retrieve the latest information and repeatedly execute the query, returning the updated information every time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
class Program
static double Square(double n)
Console.WriteLine("Computing Square(" + n + ")");
return Math.Pow(n, 2);

static void Main(string[] args)
int[] numbers = { 1, 2, 3, 4 };
var query = from n in numbers select Square(n);
Console.WriteLine("Deferred Execution");
foreach (var n in query)

Deferred Execution
Computing Square(1)
Computing Square(2)
Computing Square(3)
Computing Square(4)

More examples your can refer to

Comments or Responses

Login to post response