2

I have the following code:

List<int> nums = new List<int>();
nums.Add(1);
nums.Add(4);
nums.Add(2);
var lowNums = from n in nums
              where n%2==0
              select n;

 Console.WriteLine("Even Numbers before adding 20 :");
 foreach (var x in lowNums)
 {
   Console.WriteLine(x);
 }

 nums.Add(20);
 Console.WriteLine("Even Numbers after adding 20:");
 foreach (var x in lowNums)
 {
   Console.WriteLine(x);
 }

Here while running this,it gives me this output:

enter image description here.

But I wonder why it shows 20 because I am not running the LINQ expression after I add 20. I just display the previously calculated result. Can anyone explain this?

dcaswell
  • 3,137
  • 2
  • 26
  • 25
Prasanna
  • 337
  • 2
  • 3
  • 15
  • 1
    Running a LINQ query returns an enumerable; `foreach` iterates over it. The enumerable keeps a reference to its input and produces the output as you’re using it; a `foreach` loop creates a new enumerator each time. – Ry- Sep 25 '13 at 03:36
  • 1
    The Linq query doesn't actually get executed when you declare it. It gets executed when you *request output from it,* which is what you're doing with the `foreach` loops. Your Linq query is getting executed twice, in other words, once for each `foreach`. – Robert Harvey Sep 25 '13 at 03:45

2 Answers2

2

LINQ queries are evaluated when you iterate over lowNums using foreach

LINQ queries provide deferred execution and they don't have their own backing structure to store the elements..

It's like a conveyor belt which rolls elements only on demand..

Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • Thanks to all of you. It's because of deferred execution as I got from the above answers. It really helped me. http://stackoverflow.com/questions/7324033/what-are-the-benefits-of-a-deferred-execution-in-linq also helps understanding this concept – Prasanna Sep 25 '13 at 03:55
2

You are not running the LINQ expression, you are creating it. The expression gets executed when it is needed, which is often referred to as deferred execution.

When stepping into that code you can see that lowNums is actually of type System.Linq.Enumerable.WhereListIterator<int> which is an expression, not a result.

By looping over the expression the results are recalculated. If you want to explicitly execute the expression and store the results use .ToList() on the expression.

Gigo
  • 3,188
  • 3
  • 29
  • 40