Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat string array

Tags:

arrays

string

c#

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.

like image 1000
Elvis Silva Noleto Avatar asked Dec 28 '18 17:12

Elvis Silva Noleto


People also ask

Can I use array concat?

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.

How do I combine two arrays?

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.

Does concat mutate array?

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.

How do you join strings?

The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.


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

like image 114
Jon Skeet Avatar answered Oct 03 '22 05:10

Jon Skeet


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();
like image 39
Ousmane D. Avatar answered Oct 03 '22 03:10

Ousmane D.