0

次の配列があります。

string[] list1 = new string[2] { "01233", "THisis text" };
string[] list2 = new string[2] { "01233", "THisis text" };
string[] list3 = new string[2] { "01233", "THisis text" };
string[] list4 = new string[2] { "01233", "THisis text" };

string[][] lists = new string[][] { list1, list2, list3, list4 };

次のコードを使用して配列値を表示しようとしています。

for (int i = 0; i < lists.GetLength(0); i++)
{
     for (int j = 0; j < lists.GetLength(1); j++)
     {
        string s = lists[i, j]; // the problem is here
        Console.WriteLine(s);
     }
}
Console.ReadLine();

問題にlists[i, j];は下線が引かれ、このエラー メッセージが表示されます。Wrong number of indices inside []; expected '1'

この問題を解決する方法を教えてください。

4

4 に答える 4

7

listsは 2D 配列ではありません。配列の配列です。したがって、構文lists[i][j].

for (int i = 0; i < lists.Length; i++)
{
     for (int j = 0; j < lists[i].Length; j++)
     {
        string s = lists[i][j]; // so
        Console.WriteLine(s);
     }
}
Console.ReadLine();

Length配列の配列をチェックする方法に注意してください。ただし、他の人が言ったように、使用しないのはなぜforeachですか? foreach配列の配列には、2 つのネストされたループが必要です。


もう 1 つのオプションは、実際に 2D 配列 a を使用することstring[,]です。次のように宣言します。

string[,] lists = { { "01233", "THisis text" },
                    { "01233", "THisis text" },
                    { "01233", "THisis text" },
                    { "01233", "THisis text" }, };

次に、構文を使用して 2 つのforループを使用する、単一の.lists[i,j]foreach

于 2013-10-15T06:16:01.330 に答える
2

2D配列ではなくリストのリストがあるためです。データ構造から要素を取得するには、次のように使用する必要があります。

lists[i][j]

完全なコードは次のようになります。

for (int i = 0; i < lists.Length; i++)
{
     for (int j = 0; j < lists[i].Length; j++)
     {
        string s = lists[i][j];
        Console.WriteLine(s);
     }
}
Console.ReadLine();

しかし、実際には、あなたの場合、使用する方が良いですforeach:

foreach (var l in lists)
{
     foreach (var s in l)
     {
        Console.WriteLine(s);
     }
}
Console.ReadLine();
于 2013-10-15T06:16:08.897 に答える
0

代わりに foreach を使用する

foreach(var array in lists )
    foreach(var item in array)
    {
    //item
    }
于 2013-10-15T06:18:53.333 に答える
0

これを使ってみてください

for (int i = 0; i < lists.Length; i++)
{
    for (int j = 0; j < lists[i].Length; j++)
    {
        string s = lists[i][j];
        Console.WriteLine(s);
    }
}
Console.ReadLine();
于 2013-10-15T06:16:48.367 に答える