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.

Download Code

 
We can easily extend the above solution to concatenate an arbitrary number of byte arrays using LINQ Sum() method:

Download Code

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:

Download Code

 
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.

Download Code

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:

Download Code

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:

Download Code

 
To handle multiple arrays, change the code like this:

Download Code

That’s all about concatenating two or more byte arrays in C#.