[英]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?
如何在aspx页面中逐行显示?
Your problem is that foreach
loop for rectangle two dimensional array will return all elements from that array one at a time. 您的问题是矩形二维数组的
foreach
循环将一次返回该数组中的所有元素。 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 对于5行和10列默认
int
值的数组,我收到了下一张表
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. 如果之前已正确填充
array_questions
,则应在页面上接收表视图数据,从而导致Response.Write
调用。
A much cleaner solution would be to reuse dt
(I assume it's a DataTable ) Rows
property, which is IEnumerable<DataRowCollection>
. 一个更干净的解决方案是重用
dt
(我假设它是DataTable )的Rows
属性,该属性是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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.