Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string from array and include it's index C#

Consider the following csv

string data = "Hey, Bob, How are you";

I can flatten it to:

"Hey; Bob; How are you"

Using the following:

var s = String.Join("; ",data.Split(',').Select(d => d.Trim()).ToArray());

Is there any way I can get the index of the current item in the join and append it to the resulting string? To produce somthing along the lines of:

"Hey=0; Bob=1; How are you=2"

Does linq facilitate anything like this? Perhaps combined with a String.Format() type method?

like image 484
Billy Jake O'Connor Avatar asked May 28 '26 18:05

Billy Jake O'Connor


1 Answers

Here try this there is an index selector in the select you can use it to concatonate with each of your data pieces

var s = String.Join("; ",data.Split(',')
                  .Select((d, i) => d.Trim() + "= " + i.ToString()).ToArray());
like image 151
johnny 5 Avatar answered May 30 '26 08:05

johnny 5