4

I want to clear my doubt regarding LINQ . I have code like:

val collection = this.Employees.Where(emp => emp.IsActive)
foreach (var emp in collection)
 {
   // some stuff
 }

Now if I write code like this:

foreach (var emp in this.Employees.Where(emp => emp.IsActive))
 {
   // some stuff
 }

will this.Employees.Where(emp => emp.IsActive) be executed every iteration or it is executed only once?

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
Mohd Ahmed
  • 1,422
  • 13
  • 27

3 Answers3

7

You can think of a foreach as this:

foreach (var x in y)
    // ...

as this:

T x;
using (var enumerator = y.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        x = enumerator.Current;
        // ...
    }
}

so the two pieces of code you showed will have the same effect.

A for however is different:

for (int index = 0; index < s.Length; index++)

Here s.Length will be evaluated on each iteration of the loop.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
6

It will be executed only once. To the runtime, both statements have the exact same effect.

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
0

It will be executed only once...

Keren Caelen
  • 1,466
  • 3
  • 17
  • 38
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/faq#reputation) you will be able to [comment on any post](http://stackoverflow.com/privileges/comment). – fedorqui Jun 06 '13 at 10:22
  • ok, will remember this next time... Thank you – Keren Caelen Jun 06 '13 at 10:23
  • By the way it was an automatic comment after reviewing in http://stackoverflow.com/review/low-quality-posts/ – fedorqui Jun 06 '13 at 10:25