Concatenate two or more byte arrays in C#
This post will discuss how to combine two or more byte arrays in C#.
1. Using Buffer.BlockCopy()
method
Here’s how we can concatenate two-byte arrays using the Buffer.BlockCopy() method.
1 2 3 4 5 6 7 |
public static byte[] Combine(byte[] first, byte[] second) { byte[] bytes = new byte[first.Length + second.Length]; Buffer.BlockCopy(first, 0, bytes, 0, first.Length); Buffer.BlockCopy(second, 0, bytes, first.Length, second.Length); return bytes; } |
We can easily extend the above solution to concatenate an arbitrary number of byte arrays using LINQ Sum()
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private static byte[] Combine(byte[][] arrays) { byte[] bytes = new byte[arrays.Sum(a => a.Length)]; int offset = 0; foreach (byte[] array in arrays) { Buffer.BlockCopy(array, 0, bytes, offset, array.Length); offset += array.Length; } return bytes; } |
2. Using LINQ’s Concat()
method
Another elegant solution is to use LINQ’s Concat() method for concatenating two or more byte arrays. The following code concatenate elements of the second array into the first array:
1 2 3 |
public static byte[] Combine(byte[] first, byte[] second) { return first.Concat(second).ToArray(); } |
Here’s how we can make the above solution more generic to handle an arbitrary number of arrays. Be careful with this approach as this Concat()
chain might lead to significant performance issues.
1 2 3 4 5 6 7 8 9 10 |
public static byte[] Combine(byte[][] arrays) { byte[] bytes = new byte[0]; foreach (byte[] b in arrays) { bytes.Concat(b); } return bytes.ToArray(); } |
3. Using LINQ’s SelectMany()
method
Another simple one-liner solution to flatten any number of byte arrays into a one-byte array is LINQ’s SelectMany() method. The following code example shows how to implement this:
1 2 3 |
public static byte[] Concat(byte[][] arrays) { return arrays.SelectMany(x => x).ToArray(); } |
4. yield return
Finally, we can use the yield operator to combine multiple byte arrays, but this would return an IEnumerable
. This is demonstrated below:
1 2 3 4 5 6 7 8 9 10 |
public static IEnumerable Combine(byte[] first, byte[] second) { foreach (byte b in first) { yield return b; } foreach (byte b in second) { yield return b; } } |
To handle multiple arrays, change the code like this:
1 2 3 4 5 6 7 8 9 |
public static IEnumerable Combine(byte[][] arrays) { foreach (byte[] bytes in arrays) { foreach (byte b in bytes) { yield return b; } } } |
That’s all about concatenating two or more byte arrays in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)