【问题标题】:C# DataTable Show Single Row in ConsoleC# DataTable 在控制台中显示单行
【发布时间】:2019-09-24 03:30:00
【问题描述】:

我已经从高处和低处搜索了一种方法来显示 C# 数据表的整行,既可以通过引用行号,也可以通过简单地将行内容写入字符串变量并在控制台中显示字符串。我可以指定确切的行和字段值并显示该值,但不能显示整行。这不是 C# 中的列表,这是一个数据表。

对于下面的简单代码,我为第一个 WriteLine 得到的输出是“Horse”,但后两个 WriteLine 命令,我得到的是“System.Data.DataRow”的控制台输出,而不是整行数据。

我做错了什么?任何帮助将不胜感激。

using System;
using System.Data;
using System.Threading;

namespace DataTablePractice
{
    class Program
    {
        static void Main(string[] args)
        {

            // Create a DataTable.
            using (DataTable table = new DataTable())
            {
                // Two columns.
                table.TableName = "table";
                table.Columns.Add("Number", typeof(string));
                table.Columns.Add("Pet", typeof(string));

                // ... Add two rows.
                table.Rows.Add("4", "Horse");
                table.Rows.Add("10", "Moose");

                // ... Display first field of the first row in the console
                Console.WriteLine(table.Rows[0].Field<string>(1));

                //...Display the first row of the table in the console
                Console.WriteLine(table.Rows[0]);

                //...Create a new row variable to add a third pet
                var newrow = table.Rows.Add("15", "Snake");
                string NewRowString = newrow.ToString();

                //...Display the new row of data in the console
                Console.WriteLine(NewRowString);

                //...Sleep for a few seconds to examine output
                Thread.Sleep(4000);

            }
        }
    }
}

【问题讨论】:

标签: c# datatable row console.writeline


【解决方案1】:

当你运行这个时:

Console.WriteLine(table.Rows[0]);

实际上是这样调用的:

Console.WriteLine(table.Rows[0].ToString());  // prints object type, in this case a DataRow

如果它是您自己的课程,您可以 override ToString 返回您需要的任何内容,但您没有 DataRow 课程的选项。因此它使用here 描述的默认行为:

Object.ToString 方法的默认实现返回对象类型的完全限定名称。

您可以遍历列,例如:

var row = table.Rows[0];
for (var i = 0; i < row.Count; i++)
    Console.Write(row[i] + " : ");

或者,一种更短的方式将它们全部打印出来:

Console.WriteLine(String.Join(" : ", table.Rows[0].ItemArray));

鉴于您的数据,也许您只想引用这两个字段?

foreach (DataRow row in dt.Rows)
    Console.WriteLine($"You have {row[0]} {row[1]}(s).");

// You have 4 Horse(s).
// You have 10 Moose(s).

【讨论】:

  • 非常感谢!然后,我发现如果我使用 Console.WriteLine(String.Join(" ", newrow.ItemArray));,它会将使用 newrow 变量创建的行写入控制台。它工作得很好。 :-)