MIMI MIMI - 2 months ago 19
C# Question

Is there a LINQ way to iterate through an array of strings?

I have an array of strings like this:

test[1] = "AA";
test[2] = "BB";


I like to do things in good ways. Now I need to iterate through the array so it looks like this:

1. "AA"
2. "BB"
etc ..


I think I can do this with a for loop and index but I am wondering if I can also do it with LINQ.

Answer Source

Prior to C# 6.0:

var result = test.Select((s, i) => string.Format("{0}. {1}", i + 1, s));

Starting from C# 6.0 you can use interpolated strings:

var result = test.Select((s, i) => $"{i + 1}. {s}");