# “EnumerableToArray” (Solution)

## Answer

```
GetString: Foo
EnumerableToArray: Foo
GetString: Bar
EnumerableToArray: Bar
GetString: Foo
GetString: Bar
```

## Explanation

LINQ queries use deferred/lazy execution. It means, a LINQ query without a cast method like [ToArray()](https://github.com/andreyakinshin/problembookdotnet/tree/58c938c3d3cd146f5380f906225b46237a28506e/en/Linq/msdn.microsoft.com/library/vstudio/bb298736.aspx) or [ToList()](http://msdn.microsoft.com/library/vstudio/bb342261.aspx) is not executed immediately. The execution will be deferred until we do not explicitly require the results. Thus, the line

```csharp
var strings = GetStringEnumerable();
```

will not print anything to the console. Next, in the loop

```csharp
foreach (var s in strings)
  Console.WriteLine("EnumerableToArray: " + s);
```

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:

```csharp
return strings.ToArray();
```

Our LINQ query will be performed again. So, the lines `GetString: Foo` and `GetString: Bar` will be printed again.

[Problem](/problembookdotnet/en/linq/enumerabletoarray-p.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://andreyakinshin.gitbook.io/problembookdotnet/en/linq/enumerabletoarray-s.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
