Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 862
MIMI Avatar asked Dec 04 '22 07:12

MIMI


1 Answers

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}");
like image 80
Kirill Polishchuk Avatar answered Mar 16 '23 00:03

Kirill Polishchuk