我有
现在,我需要匹配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";
}
}
此代码运行良好,但只有问题是性能问题,需要花费很长时间才能得到结果。
请帮忙。如何改进其性能,您还有其他方法吗?
答案 0 :(得分:3)
我建议将数据组织到词典中,例如,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
//}
}