3

I have two string arrays

array1 = { "test", "test", "test" }
array2 = { "completed", "completed", "completed" }

And I want to join the strings in the two arrays (they are always the same size) -> so I want to have one array which contains

array = { "test completed", "test completed", "test completed" }

Everything I found was only joining the arrays so I have a 6 items in array. Is it possible to do this without looping through the whole array (i.e. with LINQ or something like that) ?

3
  • 4
    Anyway note that linq also loops through whole array.(not always but in this case Zip in given answers) Thats just what you dont see behind the scenes! Commented Nov 21, 2015 at 18:55
  • 1
    @M.kazemAkhgary You got to be kidding. LINQ is a magic, it never does for, foreach and any other kind of obsolete loops :-) Commented Nov 21, 2015 at 21:47
  • @M.kazemAkhgary yep, you're right, but i wanted a clean code :) thats awesome with LINQ :) Commented Nov 22, 2015 at 8:07

2 Answers 2

8

You can do it with Enumerable.Zip method like this:

var joined = array1.Zip(array2, (first, second) => first + " " + second);

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

Comments

8

You can do it with LINQ using Zip:

var res = array1.Zip(array2, (a, b) => $"{a} {b}").ToArray();

Note: If you do not have the latest compiler, use a+" "+b instead of $"{a} {b}".

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.