将2D字符串数组转换为2D int数组(多维数组)

问题描述:

我要替换 string [,] 2D数组

public static readonly string[,] first =
{
    {"2", " ", " ", " ", "1"},
    {"2", " ", "4", "3", " "},
    {" ", "2", " ", "1", " "},
    {" ", "1", " ", "3", " "},
    {"1", " ", " ", " ", " "}
};

插入 int [,] 数组

int X=-1;
public static readonly int[,] second =  
{
    {2, X, X, X, 1},
    {2, X, 4, 3, X},
    {X, 2, X, 1, X},
    {X, 1, X, 3, X},
    {1, X, X, X, X}
};

是否可以转换 string [,] 数组转换为 int [,] 数组?如果是,如何将 string [,] 转换为 int [,] ?谢谢。

Is it possible to convert a string[,] array to an int[,] array? If yes, how can I convert the string[,] into int[,]? Thank you.

实时示例: Idone

public static readonly string[,] first =
{
     {"2", " ", " ", " ", "1"},
     {"2", " ", "4", "3", " "},
     {" ", "2", " ", "1", " "},
     {" ", "1", " ", "3", " "},
     {"1", " ", " ", " ", " "}
};

转换 (请注意,当字符串= $ c>,我改用 0

Convert (note that when the string = " ", I'm putting a 0 instead):

int[,] second = new int[first.GetLength(0), first.GetLength(1)];

for (int j = 0; j < first.GetLength(0); j++)    
{
    for (int i = 0; i < first.GetLength(1); i++)
    {
        int number;
        bool ok = int.TryParse(first[j, i], out number);
        if (ok)
        {
            second[j, i] = number;
        }
        else
        {
            second[j, i] = 0;
        }
    }
}