LINQ deferred execution

A LINQ query is a recipe, not a result. It runs each time you enumerate it, against the data as it is then.

Time runs on enumerationSpace O(1) until materialisedCode C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Where returns an object that remembers the source and the filter. No element is tested until something asks for results. ToList, ToArray, Count and foreach are what trigger the work.

Code

var nums = new List<int> { 1, 2, 3 };
var big = nums.Where(n => n > 1);   // nothing runs yet
nums.Add(4);
foreach (int n in big) Console.Write(n);   // 234
var snap = big.ToList();            // runs now and stores the results
nums.Add(5);
Console.Write(snap.Count);          // still 3
public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(1, 2, 3));
        Supplier<Stream<Integer>> big = () -> nums.stream().filter(n -> n > 1);   // nothing runs yet
        nums.add(4);
        big.get().forEach(System.out::print);   // 234
        List<Integer> snap = big.get().collect(Collectors.toList());   // runs now and stores the results
        nums.add(5);
        System.out.print(snap.size());          // still 3
    }
}
int main() {
    vector<int> nums = {1, 2, 3};
    auto big = [&] {                    // nothing runs yet: a recipe, not a result
        vector<int> r; for (int n : nums) if (n > 1) r.push_back(n); return r;
    };
    nums.push_back(4);
    for (int n : big()) cout << n;      // 234
    vector<int> snap = big();           // runs now and stores the results
    nums.push_back(5);
    cout << snap.size();                // still 3
}
nums = [1, 2, 3]
big = lambda: (n for n in nums if n > 1)  # nothing runs yet
nums.append(4)
for n in big(): print(n, end="")  # 234
snap = list(big())  # runs now and stores the results
nums.append(5)
print(len(snap))  # still 3

Tips

In the .NET library

Where, Select, OrderBy, Skip and Take are deferred. ToList, ToArray, ToDictionary, Count, First, Any and Sum execute immediately.