Displaying datarows underneath each other

2019-09-08 18:22发布

How can I loop through a datatable so that the rows display neatly underneath one another,row by row.

what I have tried is the following but like this all the data displays in one column.

foreach (DataRow row in myTopTenData.Rows)
            {
                foreach (DataColumn col in myTopTenData.Columns)
                {
                    Console.Write(row[col].ToString() + " ");
                    Console.WriteLine();
                }
            }

3条回答
萌系小妹纸
2楼-- · 2019-09-08 18:31

You can use this little Linq query and String.Join:

var allFields = myTopTenData.AsEnumerable()
      .Select(r => string.Join(Environment.NewLine, r.ItemArray));
string allFieldsLines = string.Join(Environment.NewLine, allFields);

Console.Write(allFieldsLines);

Here's the non-Linq version with a loop:

foreach (DataRow row in myTopTenData.Rows)
    Console.Write(string.Join(Environment.NewLine, row.ItemArray) + Environment.NewLine);
查看更多
疯言疯语
3楼-- · 2019-09-08 18:37
foreach (DataRow row in myTopTenData.Rows)
    {
        foreach (DataColumn col in myTopTenData.Columns)
            Console.Write(string.Format("{0, -10}", row[col].ToString()));

        Console.WriteLine();
     }

string.Format"{0, -10}" will help you to align your columns (use negative values for a left alignment, positive for a right alignement, and of course 10 is an arbitrary value).

查看更多
We Are One
4楼-- · 2019-09-08 18:47

Why don't you just try with this:

foreach (DataRow row in myTopTenData.Rows)
{
    foreach (DataColumn col in myTopTenData.Columns)
    {
        Console.Write(row[col].ToString() + " ");
    }
    Console.WriteLine();
}
查看更多
登录 后发表回答