C# Program to Merge Two Arrays Easily
Concat method from System.Linq namespace like this: var merged = array1.Concat(array2).ToArray(); which combines both arrays into one.Examples
How to Think About It
Algorithm
Code
using System; using System.Linq; class Program { static void Main() { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int[] merged = array1.Concat(array2).ToArray(); Console.WriteLine("{" + string.Join(", ", merged) + "}"); } }
Dry Run
Let's trace merging array1 = {1, 2, 3} and array2 = {4, 5, 6} through the code
Start with two arrays
array1 = {1, 2, 3}, array2 = {4, 5, 6}
Use Concat to combine
array1.Concat(array2) creates a sequence: 1, 2, 3, 4, 5, 6
Convert to array
Call ToArray() to make a new array: {1, 2, 3, 4, 5, 6}
Print merged array
Output: {1, 2, 3, 4, 5, 6}
| Step | Merged Array Contents |
|---|---|
| After Concat | 1, 2, 3, 4, 5, 6 |
| After ToArray | {1, 2, 3, 4, 5, 6} |
Why This Works
Step 1: Using Concat
The Concat method joins two sequences one after another without changing the originals.
Step 2: Creating a new array
Calling ToArray() converts the combined sequence into a new array holding all elements.
Step 3: Printing the result
We use string.Join to display the array elements nicely inside curly braces.
Alternative Approaches
using System; class Program { static void Main() { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int[] merged = new int[array1.Length + array2.Length]; Array.Copy(array1, 0, merged, 0, array1.Length); Array.Copy(array2, 0, merged, array1.Length, array2.Length); Console.WriteLine("{" + string.Join(", ", merged) + "}"); } }
using System; using System.Collections.Generic; class Program { static void Main() { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; List<int> list = new List<int>(array1); list.AddRange(array2); int[] merged = list.ToArray(); Console.WriteLine("{" + string.Join(", ", merged) + "}"); } }
Complexity: O(n + m) time, O(n + m) space
Time Complexity
Merging requires visiting each element of both arrays once, so time grows linearly with total elements.
Space Complexity
A new array is created to hold all elements, so space grows linearly with combined size.
Which Approach is Fastest?
Using Array.Copy is slightly faster than LINQ Concat but less readable; Concat is best for clarity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| LINQ Concat + ToArray | O(n + m) | O(n + m) | Simple and readable merging |
| Array.Copy | O(n + m) | O(n + m) | Performance-critical manual copying |
| List AddRange | O(n + m) | O(n + m) | Flexible merging with dynamic collections |
Concat with ToArray() for a quick and readable way to merge arrays.ToArray() after Concat results in a sequence, not an array.