In this article, we will learn how to merge arrays in C#. This functionality will allow us to combine two or more arrays. Working with arrays is essential when performance matters to us since arrays work faster than many other data structures. We will use different ways to merge arrays in C#. Based on the different methods, we will compare the efficiency of each approach.

To download the source code for this article, you can visit our GitHub repository.

Let’s move on.

Prepare the Environment

First, let’s add the MergeArrayBenchmark class, which we will use to compare different ways of merging arrays.

To start with, let’s create a private field to set the default length of an array:¬†

public class MergeArrayBenchmark
{
    private static readonly int _arraySize = 1000;
}

Here, we create the _arraySize variable with the initial value set to one thousand.

Then, let’s add a private static method for creating a source array:

private static int[] GetSourceArrayPopulatedWithNumber(int number)
{
    return Enumerable.Repeat(number, _arraySize).ToArray();
}

The static Repeat method is used from the Enumerable class to generate a sequence with one repeated value for a specific number of times. In this case, we create a specific number of records with int values. At the beginning of each benchmark method, we will always initialize two new source arrays. With that, we achieve an equal starting point for all our methods.

Lastly, let’s introduce the BenchmarkDotNet library to get the benchmark results. We are going to add a MemoryDiagnoser annotation to the MergeArrayBenchmark class to get memory allocation results for each merging method:

[MemoryDiagnoser, Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class MergeArrayBenchmark

We also use the Orderer to order the results from fastest to slowest.

Using Array.Copy to Merge Arrays in C#

The first approach is the static Copy method from the Array class. This method copies a range of elements in one array to another array. Additionally, it can perform casting and boxing as required. With the Array.Copy method, we can define the source array, the initial index of the source array, the destination array, and the number of elements we want to copy. While copying from one array to another, we have to use the same data type in both arrays.

To examine all the ways, we are going to try two different methods of merging arrays using the Copy method. 

Array.Copy with New Array

In the first case, let’s use the Copy method and copy the data from both arrays to the new destination array:

[Benchmark]
public int[] MergeUsingArrayCopyWithNewArray()
{
    var firstArray = GetSourceArrayPopulatedWithNumber(1);
    var secondArray = GetSourceArrayPopulatedWithNumber(2);

    var combinedArray = new int[firstArray.Length + secondArray.Length];
    Array.Copy(firstArray, combinedArray, firstArray.Length);
    Array.Copy(secondArray, 0, combinedArray, firstArray.Length, secondArray.Length);

    return combinedArray;
}

We initialize two source arrays using the static GetSourceArrayPopulatedWithNumber method. The first array contains only the number one, while the second array contains number two values.

Then, we create a new combinedArray variable using the total size of both initial arrays. Next, we use the Array.Copy method to copy all of the data from the firstArray to the combinedArray variable as the destination array. Additionally, we pass the length of the source array to copy the data.

After that, we use the same method to copy the data from the secondArray to the combinedArray. The only difference is that we specify the source and destination index. The source index is zero, and the destination index is firstArray.Length to add the data after the last element in the array.

Note that we add the Benchmark annotation from the BenchmarkDotNet library to measure the performance when the method is run.

Array.Copy with Array.Resize

Secondly, let’s try another way of using the Copy method to change the size of an already existing array:

[Benchmark]
public int[] MergeUsingArrayCopyWithResize()
{
    var firstArray = GetSourceArrayPopulatedWithNumber(1);
    var secondArray = GetSourceArrayPopulatedWithNumber(2);

    var originalFirstArrayLength = firstArray.Length;

    Array.Resize(ref firstArray, firstArray.Length + secondArray.Length);
    Array.Copy(secondArray, 0, firstArray, originalFirstArrayLength, secondArray.Length);

    return firstArray;
}

Compared to the first method, we do not create a new array but add data from the secondArray variable to the firstArray variable.

In the first step, we store the original length of the firstArray into the originalFirstArrayLength variable. Next, we resize the firstArray passing its reference and the total length of both arrays to the Resize static method from the Array class. After that, we use the Copy method to specify the source array, the source index, the destination array, and the original lengths of both source and destination arrays.

Merging Arrays Using CopyTo

This approach is similar to the method from the previous section. Here we don’t have to use the static class to perform the merge operation. That said, the CopyTo being an instance method is the only difference between the two.

Let’s see how we can use the¬†CopyTo method to merge arrays:

[Benchmark]
public int[] MergeUsingArrayCopyTo()
{
    var firstArray = GetSourceArrayPopulatedWithNumber(1);
    var secondArray = GetSourceArrayPopulatedWithNumber(2);

    var combinedArray = new int[firstArray.Length + secondArray.Length];
    firstArray.CopyTo(combinedArray, 0);
    secondArray.CopyTo(combinedArray, firstArray.Length);

    return combinedArray;
}

Again, we create the combinedArray variable as the destination array. Next, we use the CopyTo method directly from our firstArray object to copy the data into the combinedArray variable with the index set to zero.

Finally, we perform the same functionality on the secondArray. The only difference is that we set the index to the size of the firstArray. With that, we add the secondArray records after the existing data.

Merge Arrays in C# Using LINQ Methods

In this section, we will use different LINQ methods to merge arrays.

We can use all the LINQ methods that we mention in this article from the static Enumerable class. However, we will use extension methods because they are arguably more readable and are not limited to two sequences.

For example, we can use the static Concat method:

Enumerable.Concat(firstArray, secondArray).ToArray();

And the extension Concat method:

firstArray.Concat(secondArray).ToArray();

Merging Arrays with LINQ’s Concat

The first LINQ method is the Concat method. We can use this method to append two sequences or collections to return a new sequence or collection. In our case, we will use it to concatenate two arrays. The Concat method allows the usage of duplicate elements in arrays and returns the items from the first sequence followed by the elements from the second sequence.

Like other LINQ methods in this article, this method is implemented by using deferred execution. Deferred execution in LINQ means that we can delay the evaluation of an expression until we require the actual value. We call this concept lazy loading. With that, we can improve the performance of our app.

Let’s see the actual implementation of the¬†Concat method when merging two arrays:

[Benchmark]
public int[] MergeUsingLinqConcat()
{
    var firstArray = GetSourceArrayPopulatedWithNumber(1);
    var secondArray = GetSourceArrayPopulatedWithNumber(2);

    var combinedArray = firstArray.Concat(secondArray).ToArray();

    return combinedArray;
}

In this scenario, we create the combinedArray variable by simply using the Concat method, where we append the secondArray to the firstArray. After that, we return the concatenated array because the Concat method returns IEnumerable by default.

Using LINQ’s Union to Merge Arrays

Next up is the Union method from LINQ. We can use the Union method to combine the multiple data sources into one. It is important to note that this method will remove all duplicate elements from the data sources. Based on that, it will compare references of array elements.

Union is basically Concat followed by Distinct, so we can expect the Union method to take more time to execute.

Now, let’s combine both arrays by eliminating the duplicate elements:

[Benchmark]
public int[] MergeUsingLinqUnion()
{
    var firstArray = GetSourceArrayPopulatedWithNumber(1);
    var secondArray = GetSourceArrayPopulatedWithNumber(2);

    var combinedArray = firstArray.Union(secondArray).ToArray();

    return combinedArray;
}

Similar to the previous example, we initialize the new array and assign it to the combinedArray variable with the Union method used on the firstArray to append the data from the secondArray and eliminate the duplicates.

Merging Arrays With LINQ SelectMany

The last method from LINQ is the SelectMany method. This method projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. Based on that, the SelectMany method combines the records from all arrays and converts them into one array.

We need to do a little more work when using the SelectMany method:

[Benchmark]
public int[] MergeUsingLinqSelectMany()
{
    var firstArray = GetSourceArrayPopulatedWithNumber(1);
    var secondArray = GetSourceArrayPopulatedWithNumber(2);

    var firstAndSecondArray = new[] { firstArray, secondArray };
    var combinedArray = firstAndSecondArray.SelectMany(animal => animal).ToArray();

    return combinedArray;
}

First, we create the firstAndSecondArray variable as a multidimensional array. Then, we call the SelectMany method from the firstAndSecondArray and select the objects before we convert the collection into the combinedArray variable.

Merging Arrays With Buffer.BlockCopy

In this example, we are going to use the static BlockCopy method from the Buffer class. This method copies a specified number of bytes from a source array to a destination array. In addition to that, we can set a particular offset for both source and destination arrays.

When we compare the Buffer.BlockCopy method to the Array.Copy, there is a minor difference in syntax. However, the BlockCopy method should be faster when merging arrays with primitive types:

[Benchmark]
public int[] MergeUsingBlockCopy()
{
    var firstArray = GetSourceArrayPopulatedWithNumber(1);
    var secondArray = GetSourceArrayPopulatedWithNumber(2);

    var combinedArray = new int[firstArray.Length + secondArray.Length];

    Buffer.BlockCopy(firstArray, 0, combinedArray, 0, firstArray.Length);
    Buffer.BlockCopy(secondArray, 0, combinedArray, firstArray.Length, secondArray.Length);

    return combinedArray;
}

As in the previous examples, we use the firstArray and the secondArray variables, containing the objects of type int.

However, we cannot use the BlockCopy method with the reference types in C#, only with the primitives. To avoid this, we can change classes to structures, and after that, we would be able to use pointers with the BlockCopy method.

The BlockCopy method accepts five different parameters in this case:

  • Source array
  • Source offset
  • Destination array
  • Destination offset
  • Number of records

Merge Arrays in C# Manually

We have the option to implement the merging of arrays manually. In this case, we will spend more time on implementation, and the source code will be longer. On the other hand, sometimes manually implemented functionalities can work faster since they are often adapted to our use case.

That said, let’s implement a manual way of merging arrays by adding a new combined array:

[Benchmark]
public int[] MergeUsingNewArrayManually()
{
    var firstArray = GetSourceArrayPopulatedWithNumber(1);
    var secondArray = GetSourceArrayPopulatedWithNumber(2);

    var combinedArray = new int[firstArray.Length + secondArray.Length];
    for (int i = 0; i < combinedArray.Length; i++)
    {
        if (i >= firstArray.Length)
        {
            combinedArray[i] = secondArray[i - firstArray.Length];
        }
        else
        {
            combinedArray[i] = firstArray[i];
        }
    }

    return combinedArray;
}

In the MergeUsingNewArrayManually method, we iterate through initial arrays and add elements to the destination array using the index. First, we determine the total length of the destination array and create the combinedArray variable. Then, we use a for loop and retrieve specific elements using the index. Therefore, we assign the retrieved element according to the index in the destination array.

Merge Arrays in C# Benchmark Comparison

Finally, we are going to implement the benchmark Run method which we can execute from the Program class:

BenchmarkRunner.Run<MergeArrayBenchmark>();

Benchmark Comparison with 1000 Records

Now, we can check the benchmark results with the 1000 records in each array.

So, let’s run the project in the release configuration with the dotnet run -c Release command, and get the results:

|                          Method |      Mean |     Error |    StdDev |  Gen 0 |  Gen 1 | Allocated |
|-------------------------------- |----------:|----------:|----------:|-------:|-------:|----------:|
|             MergeUsingBlockCopy |  1.120 us | 0.0262 us | 0.0767 us | 3.4237 | 0.1488 |     16 KB |
| MergeUsingArrayCopyWithNewArray |  1.200 us | 0.0281 us | 0.0823 us | 3.4237 | 0.1488 |     16 KB |
|   MergeUsingArrayCopyWithResize |  1.218 us | 0.0300 us | 0.0861 us | 3.4237 | 0.1488 |     16 KB |
|           MergeUsingArrayCopyTo |  1.276 us | 0.0317 us | 0.0900 us | 3.4237 | 0.1488 |     16 KB |
|            MergeUsingLinqConcat |  1.406 us | 0.0314 us | 0.0921 us | 3.4466 | 0.1488 |     16 KB |
|        MergeUsingLinqSelectMany |  1.523 us | 0.0328 us | 0.0968 us | 3.4790 | 0.1507 |     16 KB |
|      MergeUsingNewArrayManually |  4.339 us | 0.0861 us | 0.1816 us | 3.4180 | 0.1450 |     16 KB |
|             MergeUsingLinqUnion | 22.201 us | 0.4349 us | 0.7384 us | 1.7700 |      - |      8 KB |

The fastest method for merging arrays of integers is the MergeUsingBlockCopy method, with 1.12 microseconds. It is important to note that the Block.Copy method works only with primitive data types. With that, this is the expected result.

After that, we can see three different methods (MergeUsingArrayCopyWithNewArray, MergeUsingArrayCopyWithResize, MergeUsingArrayCopyTo) that are only 0.075 microseconds apart, and their results may vary. Then we have two different LINQ approaches which are using the Concat and the SelectMany methods, with the Concat method being slightly faster.

At last, we have our manually implemented method with 4.339 microseconds and the MergeUsingLinqUnion method with 22 microseconds.

Memory allocation is similar or identical for all approaches, with the MergeUsingLinqUnion method being the most efficient.

Benchmark Comparison with 50,000 Records

We should check the performance of the methods with different sizes of arrays, so let’s populate the arrays with 50,000 records.

To do that, let’s simply modify our _arraySize variable in the¬†MergeArrayBenchmark class:

private static readonly int _arraySize = 50000;

Now, let’s run the program again, and check the benchmark results:

|                          Method |       Mean |    Error |    StdDev |     Median |    Gen 0 |    Gen 1 |    Gen 2 | Allocated |
|-------------------------------- |-----------:|---------:|----------:|-----------:|---------:|---------:|---------:|----------:|
|             MergeUsingBlockCopy |   163.9 us |  3.40 us |   9.66 us |   163.2 us | 458.2520 | 458.2520 | 195.8008 |    782 KB |
|        MergeUsingLinqSelectMany |   178.3 us |  3.69 us |  10.35 us |   177.7 us | 282.7148 | 282.7148 | 191.1621 |    783 KB |
| MergeUsingArrayCopyWithNewArray |   216.3 us |  7.42 us |  21.16 us |   214.7 us | 254.6387 | 254.6387 | 183.8379 |    782 KB |
|   MergeUsingArrayCopyWithResize |   240.8 us | 12.81 us |  37.57 us |   229.3 us | 768.0664 | 697.7539 | 199.7070 |    782 KB |
|            MergeUsingLinqConcat |   255.5 us | 13.76 us |  39.25 us |   250.5 us | 618.6523 | 570.3125 | 213.8672 |    782 KB |
|           MergeUsingArrayCopyTo |   284.0 us | 15.11 us |  44.31 us |   279.9 us | 389.1602 | 372.0703 | 188.9648 |    782 KB |
|      MergeUsingNewArrayManually |   437.6 us | 16.04 us |  46.79 us |   422.3 us | 460.9375 | 460.9375 | 199.7070 |    782 KB |
|             MergeUsingLinqUnion | 1,552.3 us | 46.23 us | 135.60 us | 1,520.5 us | 292.9688 | 292.9688 | 109.3750 |    391 KB |

In the example with 50,000 records, we notice some differences. The static Copy method from the Block class is still in first place in terms of execution speed, with 163 microseconds. The MergeUsingLinqSelectMany method works better with a larger amount of data, so it is placed second.

Then, similarly to the previous benchmark, we have methods from the Array class, with the LINQ Concat method. The worst performance is still shown by the manually implemented method and the Union method from LINQ.

Again, memory usage is similar in all examples, with the Union method being better since it doesn’t have to allocate memory for duplicates.

Conclusion

In this article, we’ve learned how to implement different ways to merge arrays in C#. We have seen that there are many different ways to merge arrays. With different methods, we got different results. In the case of merging primitive data types in C#, the Block.Copy method proved to be the fastest. On the other hand, with reference data types, we can use the¬†Array.Copy method, or the¬†CopyTo extension method if we don’t prefer static methods.

LINQ methods are also very efficient, except for the Union method, which is expectedly slower due to duplicate removal.

Finally, we can use manually implemented methods, which turned out to be slower, but everything depends on the use case.