【发布时间】:2019-03-04 05:09:56
【问题描述】:
例如我有一个像下面这样的类:
public class MasterRecord
{
public int Id { get; set; }
public string UniqueId{ get; set; }
}
public class DetailRecord
{
public int Id { get; set; }
public int MasterRecordId { get; set; }
public string UniqueId{ get; set; }
}
我还列出了 2 个列表:
MasterList 和 DetailList
MasterList 将有大约 300,000 条记录, DetailList 将有大约 7,000,000 条记录
我需要的是循环主列表中的每条记录,并在详细列表中搜索具有相同名称的记录。
这是我的代码:
foreach (var item in MasterList)
{
var matchPersons = DetailList.Where(q => q.UniqueId == item .UniqueId).ToList();
if (matchPersons != null && matchPersons.Count() > 0)
{
foreach (var foundPerson in matchPersons)
{
//Do something with foundPerson
foundPerson.MasterRecordId = item.Id;
}
}
}
我的代码现在运行很慢,每次搜索花费我 500 毫秒才能完成,所以如果有 300k 条记录,则需要 2500 分钟 :( 才能完成。 有没有其他方法可以加快这个功能? 感谢并原谅我糟糕的英语。
更新的代码让我更清楚我想要做什么。
【问题讨论】:
-
您的列表是否来自数据库?
-
创建一个字典,这将花费时间,但在进行多次搜索时同样显着。 Dictionary
dict1 = MasterList .GroupBy(x => x.Name, y => y) .ToDictionary(x => x.Key, y => y.FirstOrDefault());或者,如果您有多个同名的人 Dictionary > dict2 = MasterList .GroupBy(x => x.Name, y => y) .ToDictionary(x => x.Key, y => y .ToList());