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
let vowels = ...computes per element and stays in scope.whereandorderbyboth reuse it without recomputing by hand.- The select builds its string from the same binding.
Keywords and builtins used here
descendingfrominletneworderbyselectstringvarwhere
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.
Step 2 of 3 in Query syntax, step 11 of 17 in LINQ in depth.