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

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

问题描述

我们有以下对象

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)?

如果数组只循环一次,我怀疑它会加速代码(并且很可能使它变慢).但是如果数组被大量操作,那么一维数组会比多维数组更有效.

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.

我提出这个问题的主要原因是看看它是否可以完成以及如何完成,而不是将其用于生产代码.

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

推荐答案

以下代码演示了如何将 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 行二维数组的中间行.

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天全站免登陆