I was reading an article about how query expressions defer executions. Does that mean when we have a collection like:
IEnumerable<int> collection = from i in integers where i % 2 == 0 select i;
It is gonna be recalculated every time the collection
is accessed?
If so, what's the general practice to deal with this? To convert into a new collection?
Also why did the C# designers chose it this way, and not something where it caches the result into the collection after the first access to the collection?
Also how does the runtime know that collection
behaves this way (defer executions), unlike another IEnumerable<T>
I might create using a List<T>
which doesn't defer executions?
Edit:
What about cases like this:
List<int> ints = new List<int> ( ) { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var even = from i in ints where i % 2 == 0 select i;
ints.AddRange ( new List<int> ( ) { 10, 20, 30, 40, 50 } );
foreach ( int i in even )
{
Console.WriteLine ( i );
}
Output:
2, 4, 6, 8, 0, 10, 20, 30, 40, 50
By caching, would the behavior be more expected?