Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 2-d array concatenation

Is there a more performant way to concatenate 2-d arrays than this?

  static void Main(string[] args)
    {

        int[][] array1 = { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } } ;             

        int[][] array2 = { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } };

        int[][] array3 = Concat(array1, array2);

    }

    private static int[][] Concat(int[][] array1, int[][] array2)
    {
        int array1Length = array1.Length;
        int array2Length = array2.Length;

        int[][] result = new int[array1Length + array2Length][];
        int i = 0;
        for (; i < array1Length; i++)
            result[i] = array1[i];

        for (; i < array2Length + array1Length; i++)
            result[i] = array2[i - array1Length];

        return result;    



    }

Edit: I would like to know if that's a good practice of deep concat of 2d array

        private static int[][] DeepConcat(int[][] array1, int[][] array2)
    {
        int array1Length = array1.Length;
        int array2Length = array2.Length;

        int[][] result = new int[array1Length + array2Length][];
        int i = 0;
        for (; i < array1Length; i++)
        {
            result[i] = new int[array1[i].Length];
            for (int j = 0; j < array1[i].Length; j++)
            {
                result[i][j] = array1[i][j];
            }
        }
        for (; i < array2Length + array1Length; i++)
        {
            result[i] = new int[array2[i - array1Length].Length];
            for (int j = 0; j < array2[i - array1Length].Length; j++)
            {
                result[i][j] = array2[i - array1Length][j];
            }

        }
        return result;

    }
like image 902
mustafabar Avatar asked Jul 07 '10 13:07

mustafabar


1 Answers

You could use a linked list of int[] instead so you don't need to re-allocate any new memory.

See LinkedList<T>, or if it doesn't perform exactly as you want for concat you can make your own easily.

like image 112
Brian R. Bondy Avatar answered Sep 19 '22 05:09

Brian R. Bondy