In this article i will describe two methods for merging two array in single array using C#
You can use the System.Collections.Generic.List class and simple Resize and Copy methods of the Array class for doing this.
Using System.Collections.Generic.List class:
private void MergeArray_method1() { string[] Arr1 = { "a", "b", "c" }; string[] Arr2 = { "d", "e", "f" }; var _List = new List(); _List.AddRange(Arr1); _List.AddRange(Arr2); string[] mainArr = _List.ToArray(); }
Using Array.Resize and Array.Copy methods:
private void MergeArray_method2() { string[] Arr1 = { "a", "b", "c","d" }; string[] Arr2 = { "d", "e", "f" }; int intlength= Arr1.Length; int destinationIndex = Arr2.Length; Array.Resize(ref Arr2, Arr1.Length+Arr2.Length); Array.Copy(Arr1, 0, Arr2, destinationIndex, intlength); }
Output of Arr2 will be:
Arr[0] = “d”
Arr[1] = “e”
Arr[2] = “f”
Arr[3] = “a”
Arr[4] = “b”
Arr[5] = “c”
Arr[6] = “d”
from above you can see there are two array Arr1 and Arr2 with length 4 and 3 respectively.And first we resize length of array Arr2 and then copy arra1 to array from index 4 to 7.
Please look at Array.Copy function:
Syntax:
Array.Copy ( sourceArray As Array,sourceIndex As Long,destinationArray As Array, destinationIndex As Long, length As Long)
where
sourceArray: The Array that contains the data to copy.
sourceIndex: represents the index in the sourceArray at which copying begins.
destinationArray: The Array that receives the data.
destinationIndex: represents the index in the destinationArray at which storing begins.
length: represents the number of elements to copy.