A deferred execution query is reevaluated when you reenumerate:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var numbers = new List() { 1, 2 };
IEnumerable query = numbers.Select(n => n * 10);
foreach (int n in query) Console.Write(n + "|"); // 10|20|
numbers.Clear();
foreach (int n in query) Console.Write(n + "|"); //
}
}
The output:
10|20|
We can save the result of a deferred executable operator with operators, such as ToArray or ToList.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var numbers = new List() { 1, 2 };
List timesTen = numbers
.Select(n => n * 10)
.ToList(); // Executes immediately into a List
numbers.Clear();
Console.WriteLine(timesTen.Count); // Still 2
}
}
The output:
2