Now, with LINQ's deferred execution, would a subsequent foreach loop execute the query only once or for each turn in the loop?
Yes, once for the loop. Actually, it may execute the query less than once - you could abort the looping part way through and the (num % 2) == 0
test wouldn't be performed on any remaining items.
Or, in other words, would there be any difference if I had:
foreach (int num in numQuery.ToList())
Two differences:
In the case above,
ToList()
wastes time and memory, because it first does the same thing as the initialforeach
, builds a list from it, and thenforeach
s that list. The differences will be somewhere between trivial and preventing the code from ever working, depending on the size of the results.However, in the case where you are going to repeatedly do
foreach
on the same results, or otherwise use it repeatedly, the then while theforeach
only runs the query once, the nextforeach
runs it again. If the query is expensive, then theToList()
approach (and storing that list) can be a massive saving.