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
  • 786
  • 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
  • 151,543
  • 27
  • 246
  • 315
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,738
  • 21
  • 105
  • 131
Embedd_0913
  • 16,125
  • 37
  • 97
  • 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,738
  • 21
  • 105
  • 131
BFree
  • 102,548
  • 21
  • 159
  • 201
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,785
  • 15
  • 73
  • 107