As per this link :http://msdn.microsoft.com/en-us/library/bb397906.aspx
namespace Linq
{
class IntroToLINQ
{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}
}
It states that query will not be exeucted , until data is iterated through foreach. But when I debugged , the data memeber of var(resultviews) contains the result values before the execution of foreach. Why this is happening?
Because your debugger is executing the query for you.
Linq is using something that is called Deferred Execution. Here is a good blog post that explains it: LINQ and Deferred Execution.
When you first execute the iterator, the query is processed and executed (in memory, to a database or in another way). Your debugger will do this for you.
Take for example the following code (you can paste this in a Console Application):
When you look at
filteredNumberson the Debugger.Break() statement you will see the following:The Results View options has the Value: “Expanding the Results View will enumerate the IEnumerable”. And that’s what’s happening in the Debugger.