I want to copy a 2D array into a second 2D array but only with the first dimension.
i.e. arrayA into arrayB but only arrayA[0] into arrayB[0].
Using a new method because using for it was too slow for my application. Is there any function or method in .NET or C# to achieve this?
Thanks in advance.
From the documentation on Array.Copy
https://msdn.microsoft.com/en-us/library/y5s0whfd(v=vs.110).aspx
When copying between multidimensional arrays, the array behaves like a long one-dimensional array, where the rows (or columns) are conceptually laid end-to-end. For example, if an array has three rows (or columns) with four elements each, copying six elements from the beginning of the array would copy all four elements of the first row (or column) and the first two elements of the second row (or column). To start copying from the second element of the third row (or column), sourceIndex must be the upper bound of the first row (or column) plus the length of the second row (or column) plus two.
To copy one dimension of the array you would need to do something like this. Imagine that we have array1
and array2
that are two-dimensional and both have corresponding sizes.
So you just do something like Array.Copy(array1, array2, array1.GetLength(0))
. Copying second dimension would be something like Array.Copy(array1, array1.GetLength(0), array2, array1.GetLength(1))
and so on.
If you want an explanation, imagine you have array that looks something like this. This is not a memory layout, just a representation as a table.
a[0,0] a[0, 1] ... a[0, n]
a[1,0] a[1, 1] ... a[1, n]
. . .
a[m, 0] a[m, 1] ... a[m, n]
So, Array.GetLength(0)
is n + 1
, Array.GetLength(1)
is m + 1
. And now imagine how it's laid out in memory.
It will look like this
a[0,0] a[0, 1] ... a[0, n] a[1,0] a[1, 1] ... a[1, n] ... a[m, 0] a[m, 1] ... a[m, n]
So, how with some calculations you can copy from any position to any by just imagining how it's laid out in memory.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments