tags:

views:

82

answers:

3

What is the term "deferred query evaluation" in the context of LINQ referes to? (please give example).

+3  A: 

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.

tvanfosson
Same as David Basarab, why are you focusing on SQL specifically, when deferred execution isn't particular to SQL at all?
Joren
Because I nearly always use LINQ in a SQL context. I've updated to make it more generic.
tvanfosson
+3  A: 

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.

David Basarab
Deferred evaluation doesn't really have anything to do in particular with SQL. Other flavors of LINQ use it as well. Since the question doesn't specify SQL, you should give a more general explanation.
Joren