2

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

How do I append some object arrays into one big object array?

For example, I have 3 elements of type: object[] and want to make one of it. How to do this?

Community
  • 1
  • 1
hansgiller
  • 973
  • 4
  • 12
  • 15

4 Answers4

12

Use this:

object[] element1 = ...;
object[] element2 = ...;
object[] element3 = ...;
var list = new List<object>();
list.AddRange(element1);
list.AddRange(element2);
list.AddRange(element3);
var result = list.ToArray();

An alternative would be:

var result = element1.Concat(element2).Concat(element3).ToArray();
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
3

You can call the method Concat on them

 var newArray = a.Concat(b).Concat(c).ToArray();
Richard
  • 106,783
  • 21
  • 203
  • 265
Nikhil
  • 3,304
  • 1
  • 25
  • 42
3

Depending on how you need to use the combined list, the most performant solution would be to feed your arrays into an iterator block and return at enumerable :

IEnumerable<object> CombineArrays ( params object[] arrays )
{
     foreach (object[] arr in arrays )
     {
          foreach (object obj in arr)
          { 
               yield return obj;
          }
     }
} 

... 

IEnumerable<object> result = CombineArrays ( array1, array2, array3);

This way will not need any additional storage to for the new combined list. The IEnumerable result will just enumerate over the arrays in turn. You can process the result using any of the Linq operators - so you can group, filter and select as much as you want.

If you need to create a writable list from this you will need to call ToList() or ToArray() on the result.

Mongus Pong
  • 11,337
  • 9
  • 44
  • 72
1

Or the good, old fashioned way:

object[] objects = new object[objects1.Length + objects2.Length + objects3.Length];
int i = 0;
for(int j = 0; j<objects1.Length; j++)
  objects[i++] = objects1[j];
for(int j = 0; j<objects2.Length; j++)
  objects[i++] = objects2[j];
for(int j = 0; j<objects3.Length; j++)
  objects[i++] = objects3[j];
Carra
  • 17,808
  • 7
  • 62
  • 75