简体   繁体   English

将二维数组转换为 C# 中的一维数组?

[英]Converting 2 dimensional array to Single dimensional in C#?

I am converting 2dimensional array to Single dimensional in C#.我正在将二维数组转换为 C# 中的一维数组。 I receive the 2 dimensional array from device (C++) and then I convert it to 1 dimensional in C#.我从设备(C++)接收二维数组,然后在 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.提前致谢。

You can use the Buffer.BlockCopy Method :您可以使用Buffer.BlockCopy 方法

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 }

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. bData.Cast<byte>()将多维数组转换为单维数组。

This will do boxing, unboxing so isn't the most performant way, but is certainly the simplest and safest.这将进行装箱,拆箱,因此不是最高效的方式,但肯定是最简单和最安全的。

easy to understend and conver to a different 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
     }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM