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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With