我想把一个二维数组中第0列的所有数据移动到一个单独的一维数组中。目前我的代码如下:
for (int x = 0; x < 100; x++) { //100 is the amount of rows in the 2D array
array1D[x] = array2D[x, 0]; //0 is the column I want to take from
}
有没有更好/更有效的方法来实现相同的结果?
我想把一个二维数组中第0列的所有数据移动到一个单独的一维数组中。目前我的代码如下:
for (int x = 0; x < 100; x++) { //100 is the amount of rows in the 2D array
array1D[x] = array2D[x, 0]; //0 is the column I want to take from
}
您无法复制列,但可以使用Buffer.BlockCopy()
复制行
class Program
{
static void FillArray(out int[,] array)
{
// 2 rows with 100 columns
array=new int[2, 100];
for (int i=0; i<100; i++)
{
array[0, i]=i;
array[1, i]=100-i;
}
}
static void Main(string[] args)
{
int[,] array2D;
FillArray(out array2D);
var first_row=new int[100];
var second_row=new int[100];
int bytes=sizeof(int);
Buffer.BlockCopy(array2D, 0, first_row, 0, 100*bytes);
// 0, 1, 2, ...
Buffer.BlockCopy(array2D, 100*bytes, second_row, 0, 100*bytes);
// 100, 99, 98, ..
}
}
这是一个扩展方法,可以从二维数组中提取一行(任意类型)
public static T[] GetRow<T>(this T[,] array, int rowIndex)
{
int n = array.GetLength(1);
var row = new T[n];
var size = Buffer.ByteLength(row);
Buffer.BlockCopy(array, rowIndex*size, row, 0, size);
return row;
}
用作
var array = new double[3, 3] {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7 ,8, 9 } };
var second = array.GetRow(1);
// {4, 5, 6}