简体   繁体   中英

How to display the values in a multi-dimensional array row-wise?

I have created a multi-dimensional array:

string[,] array_questions = new string[dt.Rows.Count, dt.Columns.Count];

for (i = 0; i < dt.Rows.Count; i++)
{
    for (j = 0; j < dt.Columns.Count; j++)
    {
        array_questions[i, j] = dt.Rows[i][j].ToString();
    }
}

foreach (string number in array_questions)
{
    Response.Write(number + "\n");
}

But it displays the entire array in one single lengthy row. How can I display it row-wise in the aspx page?

Your problem is that foreach loop for rectangle two dimensional array will return all elements from that array one at a time. You need to use indexes to access rows and columns of a two-dimensional array.

Go through each row and display each element. Then add paragraph (new line) after each row.

Example is given below:

for (int row = 0; row < array_questions.GetLength(0); row++)
{
    for (int column = 0; column < array_questions.GetLength(1); column++)
    {
        //writing data, you probably want to add comma after it
        Response.Write(array_questions[row,column]); 
    }

    //adding new line, so that next loop will start from new line
    Response.Write(Environment.NewLine);
} 

for array of 5 rows and 10 columns of default int values, I've received next table

0000000000
0000000000
0000000000
0000000000
0000000000

If you had correctly populated array_questions before, you should receive table-view data on page, resulted in Response.Write calls.


A much cleaner solution would be to reuse dt (I assume it's a DataTable ) Rows property, which is IEnumerable<DataRowCollection> . Next code achieves similar behavior, but in much cleaner fashion, and you don't need another array.

foreach (var row in dt.Rows)
{
    Response.Write(string.Join(", ", row) + Environment.NewLine);
}

will print data in next table-like fashion:

0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
for (int r = 0; r < dt.Rows.Count; r++)
{
    for (int c = 0; c < dt.Columns.Count; c++)
    {
        Response.Write(String.Join(", ", dt.Rows[r][c].ToString())); 
    }
    Response.Write("<br />");
}

what You think about this way?

   for (int r = 0; r < table.GetLength(0); r++)
    {
        for (int k = 0; k < table.GetLength(0); k++)
        {
            Console.Write((table[r, k] + " " ));
        }
        Console.Write(Environment.NewLine + Environment.NewLine);
    }
    Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM