C#:构建3D数组并用数据填充它

kam*_*ame -2 c# arrays list multidimensional-array

我到目前为止尝试的代码:

private static List<List<List<int>>> threeDArrayToThreeDList(int [,,] letters) {
    // 3d-array to 3d-list
    List<List<List<int>>> letterslist = new List<List<List<int>>>();
    List<List<int>> sublist = new List<List<int>> ();
    List<int> subsublist = new List<int> ();

    for (int i = 0; i < 2; i++) {
        letterslist.Add (sublist);
        for (int j = 0; j < 2; j++) {
            letterslist[i].Add (subsublist);
            for (int k = 0; k < 2; k++) {
                Console.WriteLine (letterslist [i][j][k]); // Element not found         
                Console.WriteLine (letters [i,j,k]);
                letterslist [i] [j] [k] = letters [i,j,k];
            }
        }
    }
    return letterslist;
}
Run Code Online (Sandbox Code Playgroud)

为什么找不到letterslist [i] [j] [k]?

Ami*_*mit 5

你的代码错了.您需要为每个"索引"创建一个列表.你的代码只创建了3个列表.

这是它应该如何工作:

private static List<List<List<int>>> threeDArrayToThreeDList(int [,,] letters) {
    // 3d-array to 3d-list
    List<List<List<int>>> letterslist = new List<List<List<int>>>();

    for (int i = 0; i < 2; i++) {
        letterslist.Add (new List<List<int>> ());
        for (int j = 0; j < 2; j++) {
            letterslist[i].Add (new List<int> ());
            for (int k = 0; k < 2; k++) {
                Console.WriteLine (letters [i,j,k]);
                letterslist [i] [j].Add(letters [i,j,k]);
            }
        }
    }
    return letterslist;
}
Run Code Online (Sandbox Code Playgroud)