0

Web アプリケーション ページの 1 つに、次のような C# コードがあります。arraylist 内の文字列配列の最初の要素を取得するにはどうすればよいですか?

コード

    protected void Button3_Click(object sender, EventArgs e)
    {
        //Array test[9] = new Array();
        ArrayList list = new ArrayList();


        list.Add(new string[] { "1", "Test1", "20", "30" });
        list.Add(new string[] { "2", "Test2", "5", "30" });
        list.Add(new string[] { "3", "Test3", "10", "30" });
        list.Add(new string[] { "4", "Test4", "20", "30" });
        list.Add(new string[] { "5", "Test5", "0", "30" });
        list.Add(new string[] { "6", "Test6", "15", "30" });
        list.Add(new string[] { "7", "Test7", "10", "30" });
        list.Add(new string[] { "8", "Test8", "20", "30" });
        list.Add(new string[] { "9", "Test9", "30", "30" });

        LabelMessages.Text = "Number of Items: " + list.Count + " Item 1 record 1: " + list[1];


    }

期待される出力

Number of Items: 9 Item 1 record 1: 1

現在の出力(これは私が望むものではありません)

Number of Items: 9 Item 1 record 1: System.String[]

したがって、次のコードがあるとします。

list.Add(new string[] { "1", "Test1", "20", "30" });

は次のように変更されます:

list.Add(new string[] { "Test1", "20", "30" });

期待される出力は次のようになります。

Number of Items: 9 Item 1 record 1: Test1
4

3 に答える 3

0

文字列配列の最初の要素が必要であり、リストの各要素は文字列配列を提示するため、リスト要素を文字列配列に型キャストし、後で配列の最初の要素にアクセスする必要があります。これ((string[])list[0])[0]により、リストの位置がゼロの配列の最初の要素が得られます。

あなたが使用しているArrayList which is not generic list、あなたが使用することができList which is generic list、あなたはなりますfree from type casting

LabelMessages.Text = "Number of Items: " + list.Count + 
                     " Item 1 record 1: " +( (string[])list[0])[0];
于 2012-11-01T06:32:48.503 に答える
0

こんにちは、要素を取得できる逆解析を達成できます。

((文字列[])リスト[0])[0]

于 2012-11-01T07:07:48.057 に答える
0

式 list[1] は、現在文字列配列であるObjectの型を返します。

これはオブジェクトであるため、 list[1][1]のように直接インデックスを付けることはできません。インデックスを付ける前に、明示的に文字列配列に変換する必要があります。

((文字列[])リスト[1])[1];

こんな感じで使えます

LabelMessages.Text = "Number of Items: " + list.Count + " Item 1 record 1: " +  ((string[])list[1])[1];
于 2012-11-01T06:43:30.383 に答える