3

How could I accomplish copying one jagged array to another? For instance, I have a 5x7 array of:

0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0

and a 4x3 array of:

0,1,1,0
1,1,1,1
0,1,1,0

I would like to be able to specify a specific start point such as (1,1) on my all zero array, and copy my second array ontop of it so I would have a result such as:

0, 0, 0, 0, 0, 0, 0
0, 0, 1, 1, 0, 0, 0
0, 1, 1, 1, 1, 0, 0
0, 0, 1, 1, 0, 0, 0
0, 0, 0, 0, 0, 0, 0

What would be the best way to do this?

4

2 回答 2

2

由于您的示例的平方性质,这似乎更适合二维数组而不是锯齿状。但无论哪种方式,你当然可以用老式的方式来做它并循环它。类似的东西(未经测试)

for (int i = 0; i < secondArray.Length; i++)
{
    for (int j = 0; j < secondArray[0].Length; j++)
    {
        firstArray[startingRow + i][startingColumn + j] = secondArray[i][j];
    }
}

编辑:和马克一样,我也有轻微的进步,略有不同但大致相同。

for (int i = 0; i < secondArray.Length; i++)
{
    secondArray[i].CopyTo(firstArray[startingRow + i], startingColumn);
}
于 2010-03-31T01:34:08.740 回答
2

即使您的输入不是矩形,这也应该有效:

void copy(int[][] source, int[][] destination, int startRow, int startCol)
{
    for (int i = 0; i < source.Length; ++i)
    {
        int[] row = source[i];
        Array.Copy(row, 0, destination[i + startRow], startCol, row.Length);
    }
}
于 2010-03-31T01:40:53.407 回答