2

Possible Duplicate:
Merging two arrays in .NET
How do I concatenate two arrays in C#?

How could I merge two string[] variables?

Example:

string[] x = new string[] { "apple", "soup", "wizard" };
string[] y = new string[] { Q.displayName, Q.ID.toString(), "no more cheese" };

I want to add these two so the content of x is:{"apple", "soup", "wizard",Q.displayName, Q.ID.toString(), "no more cheese"}; in that order. Is this possible? If the result has to go into a new string array that's fine; I just would like to know how to make it happen.

Community
  • 1
  • 1
Medic3000
  • 776
  • 4
  • 20
  • 44

4 Answers4

10

From this answer:

var z = new string[x.length + y.length];
x.CopyTo(z, 0);
y.CopyTo(z, x.length);
Community
  • 1
  • 1
StriplingWarrior
  • 142,651
  • 26
  • 235
  • 300
3

You may try:

string[] a = new string[] { "A"};
string[] b = new string[] { "B"};

string[] concat = new string[a.Length + b.Length];

a.CopyTo(concat, 0);
b.CopyTo(concat, a.Length);

Then concat is your concatenated array.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Embedd_0913
  • 15,581
  • 34
  • 96
  • 135
2

Since you mentioned .NET 2.0 and LINQ isn't available, you're really stuck doing in "manually":

string[] newArray = new string[x.Length + y.Length];
for(int i = 0; i<x.Length; i++)
{
   newArray[i] = x[i];
}

for(int i = 0; i<y.Length; i++)
{
   newArray[i + x.Length] = y[i];
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
BFree
  • 100,265
  • 20
  • 154
  • 199
1

Try this.

     string[] front = { "foo", "test","hello" , "world" };
     string[] back = { "apple", "soup", "wizard", "etc" };


     string[] combined = new string[front.Length + back.Length];
     Array.Copy(front, combined, front.Length);
     Array.Copy(back, 0, combined, front.Length, back.Length);
phadaphunk
  • 12,129
  • 15
  • 69
  • 106