我有
- 包含 2000 多行的数据表(列为 AccId 和 TerrName)。
- 包含超过 600 万条记录的大型 csv 文件(列为 AccId 和 External_ID)。
现在,我需要匹配 AccId,并且必须从 csv 文件中找到其对应的 External_ID。
目前我正在使用下面的代码实现它:
DataTable tblATL = Util.GetTable("ATL", false);
tblATL.Columns.Add("External_ID");
DataTable tbl = Util.CsvToTable("TT.csv", true);
foreach (DataRow columnRow in tblATL.Rows)
{
var query = tbl.Rows.Cast<DataRow>().FirstOrDefault(x => x.Field<string>("AccId") == columnRow["AccId"].ToString());
if (query != null)
{
columnRow["External_ID"] = query.Field<string>("External_ID");
}
else
{
columnRow["External_ID"] = "New";
}
}
此代码运行良好,但唯一的问题是性能问题,需要很长时间才能得到结果。
请帮忙。如何提高它的性能,有没有其他方法?
最佳答案
我建议将数据组织成一个字典,比如 Dictionary<String, String[]>
其中有 O(1)
时间复杂度,例如
Dictionary<String, String[]> Externals = File
.ReadLines(@"C:\MyFile.csv")
.Select(line => line.Split(',')) // the simplest, just to show the idea
.ToDictionary(
items => items[0], // let External_ID be the 1st column
items => items // or whatever record representation
);
....
String externalId = ...
String[] items = Externals[externalId];
编辑:如果相同External_ID
可以出现不止一次(见下面的评论)你必须处理重复,例如
var csv = File
.ReadLines(@"C:\MyFile.csv")
.Select(line => line.Split(',')) // the simplest, just to show the idea
Dictionary<String, String[]> Externals = new Dictionary<String, String[]>();
foreach (var items in csv) {
var key = items[0]; // let External_ID be the 1st column
var value = items; // or whatever record representation
if (!Externals.ContainsKey(key))
Externals.Add(key, value);
// else {
// //TODO: implement, if you want to deal with duplicates in some other way
//}
}
关于c# - 在大型 csv 文件 C# 中搜索字符串的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37837469/