They don’t stay stored because they don’t exist yet.
When you write
IEnumerable<int> numerosPares = from n in numeros where (n % 2) == 0 select n;
Try to think of the following terms
Query[IEnumerable<int>] numerosPares = from n in numeros where (n % 2) == 0 select n;
What are you doing and create a query
. This query
is not executed until you use it.
To force the execution of query
, and as I said, you can use the methods ToList()
or ToArray()
(and at that moment the results are brought to memory at once).
On the other hand, when using the query
in a block foreach(...)
, running it and going through each element of the result one by one.
This is one of the reasons, for example, that Resharper warns of multiple use of it query
. If the data source changes between query
, the end result will change.
See the following example:
List<int> numeros = new List<int>(){2,4,6};
IEnumerable<int> numerosPares = from n in numeros where (n % 2) == 0 select n;
Console.WriteLine("Primeira execucao");
foreach(var n in numerosPares)
{
Console.WriteLine(n); // Output 2,4,6
}
numeros.AddRange(new int[]{8,10,12});
Console.WriteLine("\nSegunda execucao");
foreach(var n in numerosPares)
{
Console.WriteLine(n); // Output 2,4,6,8,10,12
}
(Code available on Dotnetfiddle)
As you can see, the list that serves as the source changes between the executions and the printed numbers change as well.
At this time, in memory there is only the list numeros
.
So, if you want the result to be final (i.e, do not switch between executions):
List<int> numeros = new List<int>(){2,4,6};
IEnumerable<int> numerosPares = (from n in numeros where (n % 2) == 0 select n).ToList();
Console.WriteLine("Primeira execucao");
foreach(var n in numerosPares)
{
Console.WriteLine(n); // Output 2,4,6
}
numeros.AddRange(new int[]{8,10,12});
Console.WriteLine("\nSegunda execucao");
foreach(var n in numerosPares)
{
Console.WriteLine(n); // Output 2,4,6
}
(Code available on Dotnetfiddle)
In this example, the list that serves as the source changes between executions but the query
has already been executed, meaning printed numbers will no longer change even if the data source changes.
At this time, in memory there are two lists: numeros
and numerosPares
.