如何更改Jagged数组中某个点后面的所有内容?

时间:2010-05-31 23:31:23

标签: c#

假设我有一个锯齿状的数组,并且位置2,3由int 3取得。其他每个点都用int 0填充。如何用4填充2,3后面的所有位置?

0 0 0 0 0 0

0 0 0 0

0 0 0 3 0 0

0 0 0 0 0

到此:

4 4 4 4 4 4

4 4 4 4

4 4 4 3 0 0

0 0 0 0 0

我尝试过各种变体:

int a = 2;
int b = 3;

for (int x = 0; x < a; x++)
{
    for (int y = 0; y < board.space[b].Length; y++)
    {
           board.space[x][y] = 4;
    }
}

2 个答案:

答案 0 :(得分:0)

试试这个。

private static void ReplaceElements(int[][] array, int x, int y, int newValue)
{
    for (int i = 0; i <= x && i < array.Length; i++)
    {
        for (int j = 0; j < array[i].Length; j++)
        {
            if (j < y || i < x)
                array[i][j] = newValue;
        }
    }
}

演示:

int[][] array = new int[4][];
array[0] = new int[] { 0, 0, 0, 0, 0, 0 };
array[1] = new int[] { 0, 0, 0, 0};
array[2] = new int[] { 0, 0, 0, 3, 0, 0};
array[3] = new int[] { 0, 0, 0, 0, 0 };

int x = 2;
int y = 3;
int newValue = 4;

ReplaceElements(array, x, y, newValue);

foreach (int[] inner in array)
{
    Console.WriteLine(string.Join(" ", inner));
}

答案 1 :(得分:0)

最简单的方法是检查当前元素是否等于3.如果是,则通过更改某个控制变量来停止,否则将值更改为4.

bool done = false;
for (int y = 0; y < board.Size && !done; ++y)
{
    for (int x = 0; x < board.space[y].Length && !done; ++y)
    {
        if (board.space[y][x] == 3) done = true;
        else board.space[y][x] = 4;
    }
}