What is the term "deferred query evaluation" in the context of LINQ referes to? (please give example).
views:
82answers:
3Normal google search
Deferred Query Evaluation and Extension Methods Resolution
linq-deferred-query-evaluation
Any many more
With respect to LINQ, the query that you build is not evaluated until the results are actually enumerated. All you are doing when constructing the query is building an expression tree, a sequence of delegates, or using other language constructs, such as the yield statement, to defer the execution until later. The expression tree (delegates/yield) does not result in an actual query until the results of the query are needed. This allows you to build up a query and not have it evaluated until the last possible moment, keeping the result set as small as possible. For example, in LINQ to SQL we have:
// no query is executed by this statement
var query = from product in db.Products
select product;
// a select count(*) from Products is executed by this statement
var productCount = query.Count();
// a select ... from Products where ID == 3 is executed by this statement
var products = query.First( p => p.ID == 3);
// a select .. from Products is executed by this statement
foreach (var product in query)
{
...
}
A good discusion of this can be found at http://language-integrated-query.com/Linq_Deffered_Query.aspx and http://msdn.microsoft.com/en-us/library/bb308959.aspx.
Defered evaluationmeans that Linq to Sql won't go to the SQL Server database until the item is used.
You have a database table. Call it users.
If you do this.
var userList = myDataContext.User;
You haven't hit the database yet.
when you do something like.
foreach(var item in userList)
{
// do something with item
}
When the foreach gets the enumerator for the userList that is when it goes to the database for the execution.
So it is deferring the evaluation until it is used by the client code.