2

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?

  • 3
    Possible duplicate of [How do you add an index field to Linq results](http://stackoverflow.com/questions/269058/how-do-you-add-an-index-field-to-linq-results) – Nameless One Feb 12 '16 at 18:39

2 Answers2

11

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());
johnny 5
  • 19,893
  • 50
  • 121
  • 195
9

Sure - just change your Select slightly:

var s = String.Join("; ",data.Split(',')
                             .Select((d, i) => String.Format("{0}={1}",d.Trim(),i)));

note that string.Join can take an IEnumerable<T> so there's no need to call ToArray.

D Stanley
  • 149,601
  • 11
  • 178
  • 240