C# / CHAPTER 08

Collections and LINQ pipelines

Intermediate

Select, transform, and materialize sequences deliberately.

By the end of this chapter

  • Choose List for resizable data
  • Compose Where and Select
  • Recognize deferred query execution

The idea

List<T> stores a resizable sequence of a consistent element type. Add appends an item, indexing accesses an existing position, and Count reports the number of items. A LINQ pipeline describes operations over a sequence: Where keeps matching elements and Select transforms them. The order of these operations matters when the transformation changes the property used for filtering.

Many LINQ queries execute when enumerated rather than when declared. If the source list changes before enumeration, the query can observe the changed data. ToArray or ToList evaluates the query and stores its current results. Materialize when you need a snapshot; keep a deferred sequence when deliberate reevaluation is useful.

C# example
using System;
using System.Collections.Generic;
using System.Linq;
var numbers = new List<int> {1, 3};
var query = numbers.Where(n => n > 1).Select(n => n * 2);
numbers.Add(5);
Console.WriteLine(string.Join(",", query));
Result
6,10

Enumeration happens inside string.Join after the list gains five. Filtering keeps three and five, then Select doubles each retained value.

Try it yourself

Produce a snapshot of nonempty labels converted to uppercase, preserving source order.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
var values = new List<int> {2, 4};
var snapshot = values.Select(x => x + 1).ToArray();
values.Add(8);
Console.WriteLine(snapshot.Length);