当前位置:  开发笔记 > 编程语言 > 正文

如何在C#中将DataTable转换为字符串?

如何解决《如何在C#中将DataTable转换为字符串?》经验,为你挑选了4个好方法。

我正在使用Visual Studio 2005,并且有一个DataTable,其中包含两列和一些我要输出到控制台的行.我希望有类似的东西:

DataTable results = MyMethod.GetResults();
Console.WriteLine (results.ToString());

将简单的DataTable转换为字符串的最佳方法是什么(即我编码的最少量)?



1> 小智..:
string res = string.Join(Environment.NewLine, 
    results.Rows.OfType().Select(x => string.Join(" ; ", x.ItemArray)));



2> user1215839..:

迟到但这是我用的

 public static string ConvertDataTableToString(DataTable dataTable)
    {
        var output = new StringBuilder();

        var columnsWidths = new int[dataTable.Columns.Count];

        // Get column widths
        foreach (DataRow row in dataTable.Rows)
        {
           for(int i = 0; i < dataTable.Columns.Count; i++)
           {
               var length = row[i].ToString().Length;
               if (columnsWidths[i] < length)
                   columnsWidths[i] = length;
           }     
        }

        // Get Column Titles
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            var length = dataTable.Columns[i].ColumnName.Length;
               if (columnsWidths[i] < length)
                   columnsWidths[i] = length;
        }

        // Write Column titles
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            var text = dataTable.Columns[i].ColumnName;
            output.Append("|" + PadCenter(text, columnsWidths[i] + 2));
        }
        output.Append("|\n" + new string('=', output.Length) + "\n");

        // Write Rows
        foreach (DataRow row in dataTable.Rows)
        {
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                var text = row[i].ToString();
                output.Append("|" + PadCenter(text,columnsWidths[i] + 2));
            }
            output.Append("|\n");
        }
        return output.ToString();
    }

    private static string PadCenter(string text, int maxLength)
    {
        int diff = maxLength - text.Length;
        return new string(' ', diff/2) + text + new string(' ', (int) (diff / 2.0 + 0.5));

    } 



3> Christian Ha..:
using(var writer = new StringWriter()) {
    results.WriteXml(writer);
    Console.WriteLine(writer.ToString());
}

当然,这有用性取决于格式化的重要性.如果它只是一个调试转储,我发现这样的XML输出非常易读.但是,如果格式化对您很重要,那么您别无选择,只能编写自己的方法来执行此操作.


+1我发现这是一个更好的方法,而不是编写自己的格式逻辑

4> Galwegian..:

你可以使用像这样:

Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String)
    Dim sw As System.IO.StringWriter
    Dim output As String

    Console.WriteLine(label)

    ' Loop through each row in the table. '
    For Each row As DataRow In table.Rows
        sw = New System.IO.StringWriter
        ' Loop through each column. '
        For Each col As DataColumn In table.Columns
            ' Output the value of each column's data.
            sw.Write(row(col).ToString() & ", ")
        Next
        output = sw.ToString
        ' Trim off the trailing ", ", so the output looks correct. '
        If output.Length > 2 Then
            output = output.Substring(0, output.Length - 2)
        End If
        ' Display the row in the console window. '
        Console.WriteLine(output)
    Next
    Console.WriteLine()
End Sub


顺便说一下,问题是标记为C#;)
推荐阅读
php
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有