我创建了一个解决方案,该解决方案读取当前大小为 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/