Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query in foreach [duplicate]

Tags:

c#

linq

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?

like image 322
Mohd Ahmed Avatar asked Dec 12 '22 14:12

Mohd Ahmed


1 Answers

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.

like image 171
Lasse V. Karlsen Avatar answered Dec 29 '22 09:12

Lasse V. Karlsen