二维数组值替换为数组

时间:2016-12-19 03:12:30

标签: c# arrays replace

我正在使用C#。我想用另一个二维数组替换二维数组中的值。

要替换值的数组是

{
    {100, 100, 100, 100},
    {100, 100, 100, 100},
    {100, 100, 100, 100},
    {100, 100, 100, 100}
}

和,某些数组替换该数组的值是

{
    {500,500},
    {500,500}
}

我希望:

{
    {100,100,100,100},
    {100,500,500,100},
    {100,500,500,100},
    {100,100,100,100}
}

2 个答案:

答案 0 :(得分:0)

在这种情况下,您需要比较这些数组的维度: 大数组是:4x4,小是2x2(双)。因此,遍历大数组是:

bigarray[i x 2 + 1, j x 2 + 1] = smallarray [i,j].

所以公式可以是:

bigarray[i x compare_value + 1, j x compare_value + 1] = smallarray [i,j]

compare_value = bigarray/ smallaray

答案 1 :(得分:0)

简单易懂的代码有两个循环:

var bigger = new int[,]
{
    {100, 101, 102, 103, 104},
    {100, 100, 100, 100, 100},
    {100, 100, 100, 100, 100},
    {100, 100, 100, 100, 100},
};

var smaller = new int[,]
{
    {1, 2},
    {3, 4},
};

ReplaceValues (bigger, smaller, 3, 2);

和静态方法:

public static void ReplaceValues (int[,] destinationArray, int[,] replaceWith, int columnOffset, int rowOffset)
{
    for (int row = 0; row < replaceWith.GetLength (0); row++)
    {
        for (int column = 0; column < replaceWith.GetLength (1); column++)
        {
            destinationArray[row + rowOffset, column + columnOffset] = replaceWith[row, column];
        }
    }
}

当然,您应该根据您的要求升级此代码。

结果:

Result

相关问题