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?
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?
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();
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.
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];