Converting 2 dimensional array to Single dimensional in C#?

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

bData.Cast<byte>() will convert the multi-dimensional array to a single dimension.

This will do boxing, unboxing so isn't the most performant way, but is certainly the simplest and safest.


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 }