Concatenation of a C # 2-d array

Is there a more efficient way to combine 2-dimensional 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 this is a good practice for deep concat array 2d

  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; } 
+4
source share
3 answers

Instead, you can use the linked list int[] , so you do not need to reallocate any new memory.

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

+3
source

Your problem can be simplified on the same issue as this one .

So my solution for you:

  private static int[][] Concat(int[][] array1, int[][] array2) { int[][] result = new int[array1.Length + array1.Length][]; array1.CopyTo(result, 0); array2.CopyTo(result, array1.Length); return result; } 

** I can not find the link for comments below the original question. So edit my own post. *

Mustafa, I would like to ask you: are you going to copy arrays to new memory? Because your original concat method only copies references to arrays. So after creating array3 (using the original concat ()), if you change anything in array 1 and array2, then array3 will also change. I hope you know that. If you plan to have a separate memory block for array3, use only my method (or the deltreme method).

+2
source

I doubt it will be much faster, but perhaps it will be more readable:

 int[][] array3 = new int[array1.Length + array2.Length][]; Array.Copy(array1, 0, array3, 0, array1.Length); Array.Copy(array2, 0, array3, array1.Length, array2.Length); 

Edit: in the critical part of your application this may be worth it - this is a shame Buffer.BlockCopy does not work on "nested" int [] arrays: (

0
source

Source: https://habr.com/ru/post/1314955/


All Articles