LINQ and Deferred Execution of queries

Hello WPF Disciples,

LINQ is really really cool, I am in love … Today I discovered something about LINQ that made me think i was crazy for a while … Yet then I found out what is really happening and I felt really stupid …

When you create a query with LINQ the query is not executed until it’s really needed. For example

int[] list = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
int max = 5;
var query = from x in list
where x <= max
select x;

foreach (var item in query)
Console.WriteLine(item);Console.ReadKey(true);

The Result of this query is a print from 1 – 5.

The query is not executed until you reach the foreach statement. Basically LINQ will delay the execution of the query till it is really needed… This makes a lot of sense and I like the idea… BUT if you are not aware of this it can make you go crazy. For example let’s take this query and put some code that changes the state an object that is used in the query

int[] list = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
int max = 5;
var query = from x in list
where x <= max
select x;
max += 2;
foreach (var item in query)
Console.WriteLine(item);

Console.ReadKey(true);

The Result of this query is a print from 1 – 7

As you can see the result for this query is different because the max variable was changed before the query was executed… This can really make you go crazy if you are not aware of what is actually happening…Have a good LINQ time…. Regards

5 thoughts on “LINQ and Deferred Execution of queries

  1. Pingback: More LINQ and Deferred Execution « C# Disciples

  2. Pingback: Generic advanced Delegate.CreateDelegate using expression trees. | CL-UAT

Leave a comment