c# - 从大型 csv 文件 C# .Net 中删除重复记录

标签 c# .net csv

我创建了一个解决方案,该解决方案读取当前大小为 20-30 MB 的大型 csv 文件,我尝试使用查找重复行的常用技术根据用户在运行时选择的某些列值删除重复行但它太慢了,似乎程序根本无法运行。

还有什么其他技术可以用来从 csv 文件中删除重复记录

这是代码,肯定是我做错了什么

DataTable dtCSV = ReadCsv(file, columns);
//columns is a list of string List column
DataTable dt=RemoveDuplicateRecords(dtCSV, columns);

private DataTable RemoveDuplicateRecords(DataTable dtCSV, List<string> columns)
        {
            DataView dv = dtCSV.DefaultView;
            string RowFilter=string.Empty;

            if(dt==null)
            dt = dv.ToTable().Clone();

            DataRow row = dtCSV.Rows[0];
            foreach (DataRow row in dtCSV.Rows)
            {
                try
                {
                    RowFilter = string.Empty;

                    foreach (string column in columns)
                    {
                        string col = column;
                        RowFilter += "[" + col + "]" + "='" + row[col].ToString().Replace("'","''") + "' and ";
                    }
                    RowFilter = RowFilter.Substring(0, RowFilter.Length - 4);
                    dv.RowFilter = RowFilter;
                    DataRow dr = dt.NewRow();
                    bool result = RowExists(dt, RowFilter);
                    if (!result)
                    {
                        dr.ItemArray = dv.ToTable().Rows[0].ItemArray;
                        dt.Rows.Add(dr);

                    }

                }
                catch (Exception ex)
                {
                }
            }
            return dt;
        }

最佳答案

一种方法是遍历表格,构建一个 HashSet<string>包含您感兴趣的组合列值。如果您尝试添加一个已经存在的字符串,那么您有一个重复的行。像这样的东西:

HashSet<string> ScannedRecords = new HashSet<string>();

foreach (var row in dtCSV.Rows)
{
    // Build a string that contains the combined column values
    StringBuilder sb = new StringBuilder();
    foreach (string col in columns)
    {
        sb.AppendFormat("[{0}={1}]", col, row[col].ToString());
    }

    // Try to add the string to the HashSet.
    // If Add returns false, then there is a prior record with the same values 
    if (!ScannedRecords.Add(sb.ToString())
    {
        // This record is a duplicate.
    }
}

那应该很快。

关于c# - 从大型 csv 文件 C# .Net 中删除重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5272500/

相关文章:

c# - SQLBulkCopy 导致死锁

c# - 我可以在 1 个应用程序中拥有同一个 UserControl 的多个实例吗?

c# - 如何在C#中获取IP地址?

c# - 如何使用密码控件禁用 Caps Lock 警告?

c# - 未找到数据源名称且未指定默认驱动程序

c# - SQL Server CE 3.5 重复行

c# - 有谁知道如何在 ParallelExtensionExtras 中使用 IOCompletionPortTaskScheduler 和 IOTaskScheduler 以及它们的用途是什么?

python - 使用 python 和 pandas 按季节分组数据

sql - 根据第一列合并CSV表行 - sqlite

c# - 有人可以解释这种语法的各个部分,以及如何使用它吗?