typestar

let clauses in C#

Name an intermediate value once, use it three times.

var words = new[] { "kernel", "shell", "compiler", "linker" };

// let names an intermediate value inside the query
var report =
    from w in words
    let vowels = w.Count(c => "aeiou".Contains(c))
    where vowels >= 2
    orderby vowels descending, w
    select $"{w}: {vowels} vowels";

Console.WriteLine(string.Join("\n", report));

How it works

  1. let vowels = ... computes per element and stays in scope.
  2. where and orderby both reuse it without recomputing by hand.
  3. The select builds its string from the same binding.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
317
Tokens
66
Three-star pace
90 tpm

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

Type this snippet

Step 2 of 3 in Query syntax, step 11 of 17 in LINQ in depth.

← Previous Next →