Search code examples
c#.netarrays

Merging two arrays in .NET


Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array?

The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format.

I'm looking to avoid writing my own function to accomplish this if possible.


Solution

  • If you can manipulate one of the arrays, you can resize it before performing the copy:

    T[] array1 = getOneArray();
    T[] array2 = getAnotherArray();
    int array1OriginalLength = array1.Length;
    Array.Resize<T>(ref array1, array1OriginalLength + array2.Length);
    Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length);
    

    Otherwise, you can make a new array

    T[] array1 = getOneArray();
    T[] array2 = getAnotherArray();
    T[] newArray = new T[array1.Length + array2.Length];
    Array.Copy(array1, newArray, array1.Length);
    Array.Copy(array2, 0, newArray, array1.Length, array2.Length);
    

    More on available Array methods on MSDN.