CodingNeed.

1 · Values and control flow · 25 MIN

Collections, loops and LINQ

LINQ can describe a query whose execution is deferred.

Where and Select build a query; ToArray materializes its current result. Without materialization, later enumeration may observe changes to the source. This example deliberately creates a snapshot of passing scores while leaving the source list intact. Do not modify a List while enumerating it. A clear ownership contract says whether a method returns a snapshot, a live view or a lazy sequence. That contract matters as much as choosing short syntax.

Choose the materialization boundary deliberately.

Read the example

using System;
using System.Collections.Generic;
using System.Linq;
var scores = new List<int> {59,60,90};
var passing = scores.Where(score => score >= 60).ToArray();
scores.Add(100);
Console.WriteLine(string.Join(",", passing));
Console.WriteLine(scores.Count);
Check the expected output
60,90
4

Your challenge

Write a filter method returning a materialized snapshot and compare it with returning IEnumerable without ToArray.

Solution cost: O(n) filtering and O(k) materialized matches. time · Account for collection storage separately from the returned result. space

Common trap

A deferred query is not automatically a cached result.

Study the project implementation
using System;
using System.Collections.Generic;
using System.Linq;
var scores = new List<int> {59,60,90};
var passing = scores.Where(score => score >= 60).ToArray();
scores.Add(100);
Console.WriteLine(string.Join(",", passing));
Console.WriteLine(scores.Count);

Further reading: Official documentation

Next lesson: Records, nullable values and validation

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.