2012-02-17 91 views
6

我將2維數組轉換爲C#中的單維。 我收到來自設備(C++)的2維數組,然後將其轉換爲C#中的1維。 這裏是我的代碼:在C#中將二維數組轉換爲單維?

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]; 
    } 
} 

我得到期望的結果從上面的代碼,但問題是它不是執行的標準方式。 我想知道如何以標準的方式完成。 可能會做編組,我不確定。 在此先感謝。

+1

你爲什麼認爲這不是標準的方式?我看起來很好。 – 2012-02-17 03:37:05

回答

12

可以使用Buffer.BlockCopy Method

byte[,] bData = (byte[,])objTransLog; 

byte[] baData = new byte[bData.Length]; 

Buffer.BlockCopy(bData, 0, baData, 0, bData.Length); 

實施例:

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 } 
+0

這不是給我想要的結果.Buffer.BlockCopy會在循環內? – user662285 2012-02-17 04:41:51

+0

我已經添加了一個示例。 'for'循環是不需要的。 – dtb 2012-02-17 04:46:05

+0

Fine.Now問題是它會一次複製所有的數據。但我希望我的結構大小的塊(假設大小爲270)的數據,因爲我使用這個二進制數據來形成我的Structure.Structure包含幾個領域得到充滿數據,並在最後我顯示這些數據在一個網格,逐行。 – user662285 2012-02-17 04:54:04

4

簡單的方法

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(); 
1

易於understend和c不同的語言。

// 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 
    } 
} 
0

bData.Cast<byte>()將多維數組轉換爲一維。

這將做拳擊,拆箱,所以不是最高效的方式,但肯定是最簡單和最安全的。