Pranay Rana: Linq Deferred Execution

Thursday, February 25, 2010

Linq Deferred Execution

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();

Rate it on : - http://www.codeproject.com/tips/59614/Linq-Deferred-Execution.aspx

No comments:

Post a Comment