如何从一个二维数组复制行值到一维数组? [英] How to copy a row of values from a 2D array into a 1D array?

查看:1108
本文介绍了如何从一个二维数组复制行值到一维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有以下的对象

int [,] oGridCells;

也就是只与固定第一索引使用

which is only used with a fixed first index

int iIndex = 5;
for (int iLoop = 0; iLoop < iUpperBound; iLoop++)
{
  //Get the value from the 2D array
  iValue = oGridCells[iIndex, iLoop];

  //Do something with iValue
}

有没有办法在.NET中值转换为一个固定的第一个索引到一个一维数组(除通过循环的值)?

Is there a way in .NET to convert the values at a fixed first index into a single dimension array (other than by looping the values)?

我怀疑它会加快code(并且很可能使其速度较慢)如果数组只被循环一次。但是,如果该阵列被大量操纵则一维数组会比多维数组更有效。

I doubt it would speed up the code (and it may well make it slower) if the array is only being looped once. But if the array was being heavily manipulated then a single dimension array would be more efficient than a multi dimension array.

我的主要理由问这个问题是看它是否可以做,以及如何,而不是用它生产code。

My main reason for asking the question is to see if it can be done and how, rather than using it for production code.

推荐答案

以下code说明复制从2-D阵列16个字节(4整数),以一维数组。

The following code demonstrates copying 16 bytes (4 ints) from a 2-D array to a 1-D array.

int[,] oGridCells = {{1, 2}, {3, 4}};
int[] oResult = new int[4];
System.Buffer.BlockCopy(oGridCells, 0, oResult, 0, 16);

您也可以选择通过提供正确的字节偏移复制从阵列中仅有1行。本例将一个3行的2-D阵列的中间一行。

You can also selectively copy just 1 row from the array by providing the correct byte offsets. This example copies the middle row of a 3-row 2-D array.

int[,] oGridCells = {{1, 2}, {3, 4}, {5, 6}};
int[] oResult = new int[2];
System.Buffer.BlockCopy(oGridCells, 8, oResult, 0, 8);

这篇关于如何从一个二维数组复制行值到一维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆