“EnumerableToArray” (Solution)

Answer

1
GetString: Foo
2
EnumerableToArray: Foo
3
GetString: Bar
4
EnumerableToArray: Bar
5
GetString: Foo
6
GetString: Bar
Copied!

Explanation

LINQ queries use deferred/lazy execution. It means, a LINQ query without a cast method like ToArray() or ToList() is not executed immediately. The execution will be deferred until we do not explicitly require the results. Thus, the line
1
var strings = GetStringEnumerable();
Copied!
will not print anything to the console. Next, in the loop
1
foreach (var s in strings)
2
Console.WriteLine("EnumerableToArray: " + s);
Copied!
query execution will be performed. Moreover, first will be evaluated the first yield (print GetString: Foo), next the loop body will be evaluated for the first enumerable element (print EnumerableToArray: Foo). Next, the foreach loop will require the second enumerable element, the second yield will be evaluated (print GetString: Bar), the loop body will be evaluated for the second element (print EnumerableToArray: Bar).
Next, the following line will be executed:
1
return strings.ToArray();
Copied!
Our LINQ query will be performed again. So, the lines GetString: Foo and GetString: Bar will be printed again.
Problem
Copy link