我正在使用Visual Studio 2005,并且有一个DataTable,其中包含两列和一些我要输出到控制台的行.我希望有类似的东西:
DataTable results = MyMethod.GetResults(); Console.WriteLine (results.ToString());
将简单的DataTable转换为字符串的最佳方法是什么(即我编码的最少量)?
string res = string.Join(Environment.NewLine, results.Rows.OfType().Select(x => string.Join(" ; ", x.ItemArray)));
迟到但这是我用的
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)); }
using(var writer = new StringWriter()) { results.WriteXml(writer); Console.WriteLine(writer.ToString()); }
当然,这有用性取决于格式化的重要性.如果它只是一个调试转储,我发现这样的XML输出非常易读.但是,如果格式化对您很重要,那么您别无选择,只能编写自己的方法来执行此操作.
你可以使用像这样:
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