Concatenate Arrays?

  • Thread starter Thread starter Axel Dahmen
  • Start date Start date
A

Axel Dahmen

Hi,

I want to concatenate two string arrays. Is it possible to concatenate them
gracefully, i.e. without copying each element manually?

TIA,
Axel Dahmen

PS.: Here's an example of what I am about:

string[] lst1,lst2,ret;
lst1=Directory.GetFiles("C:\Temp\*.jpg");
lst2=Directory.GetFiles("C:\Temp\*.gif");

ret=lst1+lst2; // ????
 
Axel Dahmen said:
I want to concatenate two string arrays. Is it possible to concatenate them
gracefully, i.e. without copying each element manually?

It depends on exactly what you mean by "manually". Array.Copy and
Array.CopyTo will probably help you, but obviously you still need to do
the copy *somehow*.
 
Declare a new String array with the correct number of elements. Then use
the Copy method of Array to copy the two arrays into the new array. This
takes 3 lines of code but should be faster than doing two loops. Note that
this performs a shallow copy.

Robby
 
Axel Dahmen said:
Hi,

I want to concatenate two string arrays. Is it possible to concatenate them
gracefully, i.e. without copying each element manually?

I have a set of array utilities, one of which is:

public static System.Array Add( System.Array first, System.Array second )
{
Type type = first.GetType().GetElementType();
System.Array result = System.Array.CreateInstance( type, first.Length +
second.Length );

first.CopyTo( result, 0 );
second.CopyTo( result, first.Length );

return result;
}

Obviously you'll have to cast the return value.

Stu
TIA,
Axel Dahmen

PS.: Here's an example of what I am about:

string[] lst1,lst2,ret;
lst1=Directory.GetFiles("C:\Temp\*.jpg");
lst2=Directory.GetFiles("C:\Temp\*.gif");

ret=lst1+lst2; // ????
 
Back
Top