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.
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
concat() is used to merge two or more arrays. This method does not mutate the original array, but instead returns a new array populated with elements of all the arrays that were merged.
The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With