Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Linq Deferred Execution

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
17 Feb 2010CPOL 18.4K   1   1
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[^]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
GeneralRegarding Linq Pin
Lavanyaz25-Mar-10 12:54
Lavanyaz25-Mar-10 12:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.