c#将1维数组分配给2维数组语法

时间:2009-07-08 16:47:08

标签: c# arrays multidimensional-array

我想做类似的事情:

object[] rowOfObjects = GetRow();//filled somewhere else
object[,] tableOfObjects = new object[10,10];

tableOfObjects[0] = rowOfObjects;

这在某种程度上是可能的,语法是什么?

或者我需要这样做:

for (int i = 0; i < rowOfObjects.Length; i++)
{
   tableOfObjects[0,i] = rowOfObjects[i];
}

并使用循环填充二维数组行?

由于

5 个答案:

答案 0 :(得分:10)

如果您的数组是value types的数组,则可以。

int[,] twoD = new int[2, 2] {
    {0,1},
    {2,3}
};
int[] oneD = new int[2] 
    { 4, 5 };
int destRow = 1;
Buffer.BlockCopy(
    oneD, // src
    0, // srcOffset
    twoD, // dst
    destRow * twoD.GetLength(1) * sizeof(int), // dstOffset
    oneD.Length * sizeof(int)); // count
// twoD now equals
// {0,1},
// {4,5}

对象数组不可能。

注意:从.net3.5开始,这只适用于基元数组。

答案 1 :(得分:7)

不,如果你使用的是二维数组,那是不可能的。你必须复制每个项目。

如果使用锯齿状数组,它可以正常工作:

// create array of arrays
object[][] tableOfObject = new object[10][];
// create arrays to put in the array of arrays
for (int i = 0; i < 10; i++) tableOfObject[i] = new object[10];

// get row as array
object[] rowOfObject = GetRow();
// put array in array of arrays
tableOfObjects[0] = rowOfObjects;

如果您将所有数据作为行获取,那么您当然不需要将数组放入数组数组的循环,因为您无论如何都会替换它们。

答案 2 :(得分:1)

如果我有千兆字节大小的数组,我会在C ++ / CLI中使用指针进行操作,只使用memcpy而不是使用数以千计的慢速边界检查数组索引操作。

答案 3 :(得分:0)

我觉得循环最简单。

public static double[,] arraycopy(double[] 
thearray, int n, int nrow, int ncol)
{

double[] sourcearray;
double[,] newarray;
int i = 0;
int j = 0;

sourcearray = new double[n];
sourcearray = thearray;
newarray = new double[nrow, ncol];
for(i=0; i<nrow; i++)
{
    for(j=0; j<ncol; j++)
        newarray[i,j] = sourcearray[nrow*i + j]; 
}

return newarray;

}

答案 4 :(得分:-1)

所以,有点像:

    public static object[] GetRow()
    {
        object[,] test = new object[10,10];
        int a = 0;
        object[] row = new object[10];
        for(a = 0; a <= 10; a++)
        {
            row[a] = test[0, a];
        }
        return row;
    }
相关问题