They are not stored because they do not yet exist.
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 you are doing and creating 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 then the results are brought to memory at once).
On the other hand, when you use query
in a foreach(...)
block, it executes it and traverses each element of the result one by one.
This is one of the reasons, for example, that ReSharper alerts you to the multiple use of the same query
. If the data source changes between runs of 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 font changes between the runs and the printed numbers change as well.
At this moment, only the numeros
list exists in memory.
So, if you want the result to be final (i.e., do not change between runs):
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 font list changes between runs but query
has already been executed, meaning the printed numbers will no longer change even if the data source changes.
At this moment, in memory there are two lists: numeros
and numerosPares
.