Convert 2-dimensional array to one-dimensional in C #?

I am converting a 2 dimensional array to Single size in C #. I get a 2-dimensional array from the device (C ++) and then convert it to 1-dimensional in C #. Here is my code:

int iSize = Marshal.SizeOf(stTransactionLogInfo); //stTransactionLogInfo is a structure byte[,] bData = (byte[,])objTransLog; //objTransLog is 2 dimensionl array from device byte[] baData = new byte[iSize]; for (int i = 0; i < bData.GetLength(0); i++) { for (int j = 0; j < iSize; j++) { baData[j] = bData[i, j]; } } 

I get the desired result from the code above, but the problem is that this is not a standard implementation method. I want to know how this can be done in a standard way. Maybe Marshall, I'm not sure. Thanks in advance.

+6
source share
4 answers

You can use the Buffer.BlockCopy method:

 byte[,] bData = (byte[,])objTransLog; byte[] baData = new byte[bData.Length]; Buffer.BlockCopy(bData, 0, baData, 0, bData.Length); 

Example:

 byte[,] bData = new byte[4, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } }; byte[] baData = new byte[bData.Length]; Buffer.BlockCopy(bData, 0, baData, 0, bData.Length); // baData == { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 } 
+12
source

Simplest method

 int iSize = Marshal.SizeOf(stTransactionLogInfo); //stTransactionLogInfo is a structure byte[,] bData = (byte[,])objTransLog; //objTransLog is 2 dimensionl array from device byte[] baData = bData.Cast<byte>().ToArray(); 
+4
source

easy to understand and switch to another language.

 // Create 2D array (20 rows x 20 columns) int row = 20; int column = 20; int [,] array2D = new int[row, column]; // paste into array2D by 20 elements int x = 0; // row int y = 0; // column for (int i = 0; i < my1DArray.Length; ++i) { my2DArray[x, y] = my1DArray[i]; y++; if (y == column) { y = 0; // reset column x++; // next row } } 
+1
source

bData.Cast<byte>() converts a multidimensional array into one dimension.

This will make boxing, unboxing, so this is not the most efficient way, but certainly the easiest and safest.

0
source

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


All Articles