Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Concatenate two arrays?

0 views
Skip to first unread message

Tim Sweeney

unread,
Jul 21, 2002, 4:48:07 AM7/21/02
to
Is there a reasonable way to concatenate two arrays in C#? As far as I can
see:

1. There is no built-in operator to concatenate arrays.

2. There is no way of writing a general array concatenation function because
C# doesn't support templates (as one would use in C++) and doesn't support
low-level hacking to work around the need for casts (as one would use in C).

So, every time I want to concatenate two arrays, I have to create a new
array of the proper length, then copy both arrays' data into the new array -
something that takes 3 big complex lines of code, when I really want to
just say "a+b".

Any thoughts? (Please pardon me if I'm missing something obvious!)

-Tim


Antonio Cangiano

unread,
Jul 21, 2002, 5:03:20 AM7/21/02
to
You can use the overload of operators.

--
"C# is the future."
Where Do You Want To Go Today?


Tom Jones

unread,
Jul 21, 2002, 9:07:35 AM7/21/02
to
One option (other than creating your own wrapper) is to use ArrayList
instead of array.

ArrayList list1 = new ArrayList(...);
// Fill list1 with data

ArrayList list2 = new ArrayList(...);
// Fill list2 with data

// Add the contents of list1 to list2
list2.AddRange(list1);

// Or...
ArrayList list3 = new ArrayList();
list3.AddRange(list1);
list3.AddRange(list2);

HTH,
Tom


"Tim Sweeney" <t...@epicgames.com> wrote in message
news:esfLONJMCHA.2452@tkmsftngp08...

Mike Schilling

unread,
Jul 21, 2002, 11:16:48 AM7/21/02
to
"Tim Sweeney" <t...@epicgames.com> wrote in message
news:esfLONJMCHA.2452@tkmsftngp08...

If what you want to be able to do is iterate through both of them, it would
be pretty trivial to write a List that iterates through two arrays (or a
List of arrays). Of course, this requires a cast every time you get a
member from the List, and for scalar arrays adds a boxing/unboxing operation
as well.


Thong (Tum) Nguyen

unread,
Jul 22, 2002, 8:30:45 AM7/22/02
to
Hi Tim,

You can write a generic array concatenation function.

Here's an example of how to do it (only works with 1D arrays).

public static Array ArrayAdd(Array a1, Array a2)
{
Array array;
array = Array.CreateInstance(a1.GetType().GetElementType(), a1.Length +
a2.Length);

Array.Copy(a1, 0, array, 0, a1.Length);
Array.Copy(a2, 0, array, a1.Length, a2.Length);

return array;
}

You can test it with:

string[] ss1 = {"1", "2", "3"};
string[] ss2 = {"4", "5", "6"};
string[] ss3;

ss3 = (string[])ArrayAdd(ss1, ss2);

Hope that helps,

-Tum

"Tim Sweeney" <t...@epicgames.com> wrote in message
news:esfLONJMCHA.2452@tkmsftngp08...

0 new messages