We have many ways to merge the two arrays in C# using the below methods,
- Using
Array.Copy()
- Using
Array.CopyTo()
- Using
Array.Resize()
- Using
AddRange()
Merge two Arrays using Array.Copy()
The Array.Copy()
method copies a range of elements from one array to another array. In the below example, we used the Array.Copy() method to copy the both the array elements into another array.
using System;
namespace MergeTwoArrays
{
class Program
{
static void Main()
{
int[] firstArray = { 100, 200, 300, 400 };
int[] secondArray = { 500, 600, 700, 800 };
int[] result = new int[firstArray.Length + secondArray.Length];
Array.Copy(firstArray, result, firstArray.Length);
Array.Copy(secondArray, 0, result, firstArray.Length, secondArray.Length);
Console.WriteLine(String.Join(",", result));
Console.ReadKey();
}
}
}
Output:
100,200,300,400,500,600,700,800
Merge two Arrays using Array.CopyTo()
The Array.CopyTo() method is used to copy an array in C#. In the below example, we are copying all the arrays to empty arrays using CopyTo()
method.
using System;
using System.Collections.Generic;
namespace MergeTwoArrays
{
class Program
{
static void Main()
{
int[] firstArray = { 100, 200, 300, 400 };
int[] secondArray = { 500, 600, 700, 800 };
int[] result = new int[firstArray.Length + secondArray.Length];
firstArray.CopyTo(result, 0);
secondArray.CopyTo(result, firstArray.Length);
Console.WriteLine(String.Join(",", result));
Console.ReadKey();
}
}
}
Output:
100,200,300,400,500,600,700,800
Merge two Arrays using Array.Resize()
The Array.Resize() method is used to resize a one-dimensional array in C#. In this example, we use Array.Resize()
with Array.Copy()
methods to copy the two arrays.
using System;
namespace MergeTwoArrays
{
class Program
{
static void Main()
{
int[] firstArray = { 100, 200, 300, 400 };
int[] secondArray = { 500, 600, 700 };
int firstArrayLength = firstArray.Length;
Array.Resize<int>(ref firstArray, firstArray.Length + secondArray.Length);
Array.Copy(secondArray, 0, firstArray, firstArrayLength, secondArray.Length);
Console.WriteLine(String.Join(",", firstArray));
Console.ReadKey();
}
}
}
Output:
100,200,300,400,500,600,700
Merge two Arrays using AddRange()
The AddRange() method is used to add the specified array elements at the end of the List<T>
. The following example demonstrates how to add the 2 arrays using AddRange() method.
using System;
using System.Collections.Generic;
namespace MergeTwoArrays
{
class Program
{
static void Main()
{
int[] firstArray = { 100, 200, 300, 400 };
int[] secondArray = { 500, 600 };
List<int> listOfArray = new List<int>(firstArray.Length + secondArray.Length);
listOfArray.AddRange(firstArray);
listOfArray.AddRange(secondArray);
Console.WriteLine(String.Join(",", listOfArray.ToArray()));
Console.ReadKey();
}
}
}
Output:
100,200,300,400,500,600
Comments (0)