c# - 将 DataTable 转换为 CSV 的最有效方法

标签 c# performance csv datatable

我正在使用 DataTable,我需要将它们转换为 CSV 文件格式。我正在使用的大多数表都有超过 50,000 条记录,因此我尽量减少转换它们所需的时间。

这是我目前的方法:

    public static string table_to_csv(DataTable table)
    {
        string file = "";

        foreach (DataColumn col in table.Columns)
            file = string.Concat(file, col.ColumnName, ",");

        file = file.Remove(file.LastIndexOf(','), 1);
        file = string.Concat(file, "\r\n");

        foreach (DataRow row in table.Rows)
        {
            foreach (object item in row.ItemArray)
                file = string.Concat(file, item.ToString(), ",");

            file = file.Remove(file.LastIndexOf(','), 1);
            file = string.Concat(file, "\r\n");
        }

        return file;
    }

有什么办法可以提高这种方法的效率吗?欢迎提出任何修改和想法!

最佳答案

使用 System.Text.StringBuilder对于巨大的字符串 - 这非常快。 我实现了这个:

public static string DataTableToCSV(this DataTable datatable, char seperator)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < datatable.Columns.Count; i++)
    {
        sb.Append(datatable.Columns[i]);
        if (i < datatable.Columns.Count - 1)
            sb.Append(seperator);
    }
    sb.AppendLine();
    foreach (DataRow dr in datatable.Rows)
    {
        for (int i = 0; i < datatable.Columns.Count; i++)
        {
            sb.Append(dr[i].ToString());

            if (i < datatable.Columns.Count - 1)
                sb.Append(seperator);
        }
        sb.AppendLine();
    }
    return sb.ToString();
}

关于c# - 将 DataTable 转换为 CSV 的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28503437/

相关文章:

silverlight - UseLayoutRounding = true时的性能影响

python - 如何在 FastAPI 中上传 CSV 文件并将其转换为 JSON?

c# - 等待 Console.ReadLine()

c# - Where() with Replace() in Dictionary.Where(p => p.Key is T)

c# - DataGridView 为列中的某些单元格着色

python - 在数据框中动态拆分行

javascript - 得到 "Cannot read property ' getAttribute' of null“错误

c# - 在 Visual Studio 中调试时如何强制出现异常?

c - 就地替换字符串中的字符

android - 如何限制Android模拟器上的互联网连接速度?