If you've stumbled upon this post, it probably means that you're looking for a way to solve this simple task:
1 2 3 4 5 6 7 |
int[] a = new int [] { 1, 2, 3, 4, 5 }; int[] b = new int [] { 6, 7, 8 }; int[] c = new int [] { 9, 10 }; int[] z = // a merge of a + b + c Debug.Assert(z.SequenceEqual(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })); |
There are a number of methods that can be used, such as:
- Instantiate a List<int> , use the AddRange method to add the arrays one at a time, and then use ToArray() to transform it into an array;
- Instantiate an int[] with a size equal to the sum of a.Length , b.Length and c.Length and then use the CopyTo() method to copy the array contents there.
... And so on.
Well, this is the one-liner I've came up with:
1 2 3 4 5 |
int[] z = new List<string>() .Concat(a) .Concat(b) .Concat(c) .ToArray(); |
The good thing about the Concat() method is that we can use it at initialization level, for example to define a static concatenation of static arrays:
1 2 3 4 5 6 7 8 |
public static int[] a = new int [] { 1, 2, 3, 4, 5 }; public static int[] b = new int [] { 6, 7, 8 }; public static int[] c = new int [] { 9, 10 }; public static int[] z = new List<string>() .Concat(a) .Concat(b) .Concat(c) .ToArray(); |
This cannot be done using the other workarounds.
However, doing this has two caveats that you need to consider:
- The Concat method creates an iterator over both arrays: it does not create a new array, thus being efficient in terms of memory used: however, the subsequent ToArray will negate such advantage, since it will actually create a new array and take up the memory for the new array.
-
As this StackOverflow thread clearly explains, Concat will be rather inefficient for large arrays: it should only be used for medium-sized arrays (up to 10000 elements each).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/// <summary> /// Concatenates two or more arrays into a single one. /// </summary> public static T[] Concat<T>(params T[][] arrays) { // return (from array in arrays from arr in array select arr).ToArray(); var result = new T[arrays.Sum(a => a.Length)]; int offset = 0; for (int x = 0; x < arrays.Length; x++) { arrays[x].CopyTo(result, offset); offset += arrays[x].Length; } return result; } |
1 |
int[] z = (from array in new[] { a, b, c } from arr in array select arr).ToArray(); |
Keep in mind that you can gain even bigger performance advantage by using Buffer.BlockCopy over Array.CopyTo, as explained here: however, you won't gain much, and I tend to favor the Array.CopyTo method as it's much more readable when dealing with arrays.