Tuesday, January 06, 2009

LINQ with Delphi Prism #2 : Deferred Execution

As said in this previous post Delphi Prism supports LINQ all the way so all the LINQ feature just work in Delphi Prism.

Deferred Execution
One of the key features of LINQ is Deferred Execution. That means that a LINQ query does not execute until data is demanded, for except by an iteration through a list. This makes it possible to make a complex query without execution each part of the query seperately.

However, there is one exceptions to the rule, a LINQ query executes immediately when you use a function that must iterate over the list for its result like, for example Sum(), Count(), ToList() etc.

//Example of deferred execution or lazy execution
//-------------------------------------------
var Numbers := new List<integer>;
Numbers.Add(
1);
var DoubledList : sequence of integer
:
= Numbers.Select(n->n*2);
// Query not yet executed!
// Add another number to the list
Numbers.Add(2);

//At this point query is executed
//Result "2--4"
for i : Integer in DoubledList do begin
Result :
= Result + i.ToString + '--';
end;
MessageBox.Show(Result);


//Example of direct execution
//-------------------------------------------
var Numbers := new List<integer>;
Numbers.Add(
1);
Numbers.Add(
2);
//Query executed here
var Sum := (Numbers.Select(n->n*2)).Sum();
Numbers.Add(
3);
Numbers.Add(
4);
//Would expect 20, but result is only 6
MessageBox.Show(Sum.ToString);

No comments: