65.9K
CodeProject is changing. Read more.
Home

Linq Deferred Execution

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (3 votes)

Feb 18, 2010

CPOL
viewsIcon

18612

To understand how execution take place consider below code: //Query not going to execute at this pointvar query = from customer in db.Customers where customer.City == "Paris" select customer; Most of the people think that the query gets...

To understand how execution take place consider below code:
//Query not going to execute at this point
var query = from customer in db.Customers  
            where customer.City == "Paris" 
            select customer; 
Most of the people think that the query gets executed at this place but the its not right its get executed when I use query collection for example
//Query get executed at this point
foreach( customer c in query) 
{
  // your code 
}
Or
int count = (from customer in db.Customers  
            where customer.City == "Paris" 
            select customer).Count();
or to .ToList() or any other function which cause execution. Consider another scenario I write code like this
var query = from customer in db.Customers  
            where customer.City == "Paris" 
            select customer;
than change code to below line
query = from customer in db.Customers  
            where customer.City == "Mumbai" 
            select customer; 
and than try to use query object
//it get count of all customer which is related to city Mumbai rather than paris.

int count = query.Count(); 
Find more details[^]