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
Select((name, i) => ...)hands each element with its position.- Numbering starts at 0; the template adds 1 for display.
- The second example labels pie slices the same way.
Keywords and builtins used here
newstringvar
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.
Step 1 of 3 in Shaping, step 1 of 17 in LINQ in depth.