Elvis Silva Noleto
Elvis Silva Noleto

Reputation: 119

Concat string array

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.

Upvotes: 7

Views: 414

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56433

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();

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500515

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.)

Upvotes: 29

Related Questions