typestar

Where & Select in C#

Filter and transform sequences without writing a loop.

var numbers = Enumerable.Range(1, 10);

var evens = numbers.Where(n => n % 2 == 0);
var squares = numbers.Select(n => n * n);

Console.WriteLine(string.Join(",", evens));
Console.WriteLine(string.Join(",", squares.Take(4)));

// chained: the query only runs when something asks for results
var firstBig = numbers.Select(n => n * n).First(sq => sq > 20);
Console.WriteLine(firstBig);

How it works

  1. Where keeps what the predicate accepts; Select maps each element.
  2. Queries are lazy: nothing runs until Join or First asks for results.
  3. First(sq => sq > 20) stops at the first match, not the whole list.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
382
Tokens
106
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 1 of 3 in LINQ, step 22 of 29 in Language basics.

← Previous Next →