Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 2 dimensional array to Single dimensional in C#?

I am converting 2dimensional array to Single dimensional in C#. I receive the 2 dimensional array from device (C++) and then I 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 above code, but the problem is it is not the standard way of implementation. I want to know how it can be done in a standard way. May be doing Marshalling , I am not sure. Thanks in advance.

like image 672
Bokambo Avatar asked Feb 17 '12 03:02

Bokambo


3 Answers

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.

like image 184
stevec Avatar answered Sep 17 '22 16:09

stevec


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 }
like image 30
dtb Avatar answered Sep 17 '22 16:09

dtb


If 2-D array's column size is dynamic, below code is usable:

    public static T[] Convert2DArrayTo1D<T>(T[][] array2D)
    {
        List<T> lst = new List<T>();
        foreach(T[] a in array2D)
        {
            lst.AddRange(a);
        }
        return lst.ToArray();
    }
like image 22
eric xu Avatar answered Sep 21 '22 16:09

eric xu