Here's my answer:
int[] z = new List<string>()
.Concat(a)
.Concat(b)
.Concat(c)
.ToArray();
This method can be used at initialization level, for example to define a static concatenation of static arrays:
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();
However, it comes with 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 @Jodrell said,
Concat would be rather inefficient for large arrays: it should only be used for medium-sized arrays.
If aiming for performance is a must, the following method can be used instead:
/// <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;
}
Or (for one-liners fans):
int[] z = (from arrays in new[] { a, b, c } from arr in arrays select arr).ToArray();
Although the latter method is much more elegant, the former one is definitely better for performance.
For additional info, please refer to this post on my blog.