7

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.

1
  • Use 2 for loop and a return array Commented Dec 28, 2018 at 17:41

2 Answers 2

29

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.