Query Execution in Linq- Deferred and Immediate execution

219
Views
1
Answers

What is Deferred and Immediate execution in Linq? when is the data actually pulled from the database when using linq?

edit | flag
Mad Maddy
Asked on: Feb 02, 2012 at 3:21AM

1 Answers

118
3
118

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately

Deferred query execution

In a LINQ 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.

var productsQuery =
                   
from p in context.Products
                   
select p;

           
IQueryable Products = productsQuery.Where(p => p.Name == "CUP");

           
Console.WriteLine("Products with name CUP:");

           
foreach (var product in Products) // query is actually executed here
           
{
               
Console.WriteLine(product.Name);
               
Console.WriteLine(product.Details);
           
}

Immediate Execution

LINQ queries that return a singleton value are executed immediately. Some examples of singleton queries are Average, Count, First, and Max. These execute immediately because the query must produce a sequence to calculate the singleton result.

var productsQuery =
                   
(from p in context.Products where p.Name=="CUP"
                   
select p).Count();


           
Console.WriteLine("Number of Products with name CUP:",productsQuery);

You can also force immediate execution. This is useful when you want to cache the results of a query. To force immediate execution of a query that does not produce a singleton value, you can call the ToList method, the ToDictionary method, or the ToArray method on a query or query variable.

 Product[] prodArray = (
       
from p in products
       
orderby p.Price descending
       
select p).ToArray();

           
Console.WriteLine("Product price from highest to lowest:");
           
foreach (var product in prodArray)
           
{
               
Console.WriteLine(product.ListPrice);
           
}  
edit | flag
Gokul A
Answered on: Feb 02, 2012 at 3:36AM

Post your Answer

Search

Welcome to Ask Amoeba!
This is 100% free and interactive site for sharing professional Questions and Answers, Opensource projects, Interview questions.
Learners, beginners, Experts stop and share your knowledge and ideas!

Browse Categories

Browse Tags