typestar

Select with index in C#

The overload that numbers a list without a counter variable.

var crew = new[] { "Ada", "Grace", "Alan", "Edsger" };

// Select can hand over the index along with the element
var numbered = crew.Select((name, i) => $"{i + 1}. {name}");
Console.WriteLine(string.Join("\n", numbered));

var shares = new[] { 40, 30, 20, 10 };
var labels = shares.Select((v, i) => $"slice {i}: {v}%");
Console.WriteLine(string.Join(" | ", labels));

How it works

  1. Select((name, i) => ...) hands each element with its position.
  2. Numbering starts at 0; the template adds 1 for display.
  3. The second example labels pie slices the same way.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
366
Tokens
93
Three-star pace
90 tpm

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

Type this snippet

Step 1 of 3 in Shaping, step 1 of 17 in LINQ in depth.

Next →