将二维数组转换为 C# 中的一维数组? [英] Converting 2 dimensional array to Single dimensional in C#?
本文介绍了将二维数组转换为 C# 中的一维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 C# 中将二维数组转换为一维数组.我从设备(C++)接收二维数组,然后在 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.
推荐答案
您可以使用 Buffer.BlockCopy 方法:
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 }
这篇关于将二维数组转换为 C# 中的一维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文