C# 将特定2D数组索引下的数据移动到1D数组
我想将所有数据从二维数组的第0列移动到单独的一维数组。到目前为止,我有:C# 将特定2D数组索引下的数据移动到1D数组,c#,arrays,multidimensional-array,C#,Arrays,Multidimensional Array,我想将所有数据从二维数组的第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 } for(int x=0;x
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
}
for(int x=0;x<100;x++){//100是二维数组中的行数
array1D[x]=array2D[x,0];//0是我要从中获取的列
}
是否有更好/更有效的方法来实现相同的结果?您不能复制列,但可以使用
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}