繁体   English   中英

如何在多维数组中按行显示值?

[英]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.

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