[英]How to display the values in a multi-dimensional array row-wise?
我創建了一個多維數組:
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");
}
但它將整個數組顯示在一個冗長的行中。 如何在aspx頁面中逐行顯示?
您的問題是矩形二維數組的foreach
循環將一次返回該數組中的所有元素。 您需要使用索引來訪問二維數組的行和列。
遍歷每一行並顯示每個元素。 然后在每行之后添加段落(換行)。
示例如下:
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);
}
對於5行和10列默認int
值的數組,我收到了下一張表
0000000000
0000000000
0000000000
0000000000
0000000000
如果之前已正確填充array_questions
,則應在頁面上接收表視圖數據,從而導致Response.Write
調用。
一個更干凈的解決方案是重用dt
(我假設它是DataTable )的Rows
屬性,該屬性是IEnumerable<DataRowCollection>
。 下一代碼實現了類似的行為,但是更加清晰,並且您不需要另一個數組。
foreach (var row in dt.Rows)
{
Response.Write(string.Join(", ", row) + Environment.NewLine);
}
將以下一種表格形式打印數據:
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 />");
}
你怎么看待這種方式?
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.