Does this linq query execute on each iteration of the for-each loop?

In another question on SO, I answered with code similar to the one below and received a comment that the LINQ query was probably evaluated at each for / each iteration. It's true?

I know that LINQ queries are not executed before its elements are evaluated, so it seems possible that in such a way that an iteration of the result can make it work on each iteration?

Dim d = New Dictionary(Of String, String)() d.Add("Teststring", "Hello") d.Add("1TestString1", "World") d.Add("2TestString2", "Test") For Each i As String In From e In d Where e.Value.StartsWith("W") Select e.Key MsgBox("This key has a matching value:" & i) Next 
+6
enumeration linq
source share
3 answers

NO ... in foreach, "GetEnumerator" is called only once (ever), and this will be used in the future.

EDIT: here I am making an expression that the result set is temporarily stored ... this is only true for some cases ... not for this, so I took it.

EDIT: Please forgive this for being too verbose ... but I wanted to show you what is happening ... so here is the console application :)

 using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { foreach (string item in MyCustomEnumerator() .Where(item => item.StartsWith("abc"))) { Console.WriteLine(item); } } static IEnumerable<string> MyCustomEnumerator() { Console.WriteLine(DateTime.Now); yield return "abc1"; Console.WriteLine(DateTime.Now); yield return "abc2"; Console.WriteLine(DateTime.Now); yield return "abc3"; Console.WriteLine(DateTime.Now); yield return "xxx"; } } } 

EDIT: this will result in using DateTime, then abc1, then DateTime, then abc2, then DateTime, then abc3, then DateTime.

+7
source share

I believe that it will be launched the first time it is reached, and will enumerate with all the relevant values. What you actually get is an enumeration for this enumeration.

+1
source share

I looked at the FOR EACH ... NEXT statement, and Visual Basic only evaluates the collection once before the loop starts, so it should not run the query at each iteration.

The number of iterations. Visual Basic evaluates the collection only once, before the start of the cycle. If your element changes the statement block or group, these changes do not affect the iteration of the loop.

0
source share

All Articles