Linq query in foreach

I want to clarify my doubts about LINQ. I have code like:

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

Now, if I write the code as follows:

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

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

+4
source share
3 answers

You can think of foreach like this:

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

like this:

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

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

A for however differs:

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

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

+6
source

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

+5
source

It will be executed only once ...

0
source

Source: https://habr.com/ru/post/1484801/


All Articles