Concat string array

Viewed 374

I have two string arrays, I want them to become one with differente values like this:

string[] array1 = { "Jhon", "Robert", "Elder" };
string[] array2 = { "Elena", "Margareth", "Melody" };

I want an output like this:

{ "Jhon and Elena", "Robert and Margareth", "Elder and Melody" };

I've used string.Join, but it works only for one string array.

2 Answers

It sounds like you want Zip from LINQ:

var result = array1.Zip(array2, (left, right) => $"{left} and {right}").ToArray();

Zip takes two sequences, and applies the given delegate to each pair of elements in turn. (So the first element from each sequence, then the second element of each sequence etc.)

Another solution assuming both arrays will always be of the same length.

var result = array1.Select((e, i) => $"{e} and {array2[i]}").ToArray();

Though I have to admit this is not as readable as Zip shown in the other answer.

Another solution would be via Enumerable.Range:

Enumerable.Range(0, Math.Min(array1.Length, array2.Length)) // drop Min if arrays are always of the same length
          .Select(i => $"{array1[i]} and {array2[i]}")
          .ToArray();
Related