【发布时间】:2020-12-19 17:55:53
【问题描述】:
我有这个型号的列表
public Class Contact
{
public string MobileNumber {get;set;}
public string PhoneNumber2 {get;set;}
}
我有一个方法可以将此列表与电话号码列表进行比较并返回不匹配的值
private List<ContactDto> GetNewContactsNotFoundInCrm(ContactPostModel model)
{
var duplicates = GetAllNumbers(); // Returns a List<string> of 5 million numbers
var mobile = duplicates.Select(x => x.MobilePhone).ToList();
var telephone2 = duplicates.Select(x => x.Telephone2).ToList();
// I'm trying to compare Telephone2 and MobilePhone against the
// duplicates list of 5 million numbers. It works, but it's slow
// and can take over a minute searching for around 5000 numbers.
return model.Contacts
.Where(y =>
!mobile.Contains(y.Phonenumber.ToPhoneNumber()) &&
!telephone2.Contains(y.Phonenumber.ToPhoneNumber()) &&
!mobile.Contains(y.Phonenumber2.ToPhoneNumber()) &&
!telephone2.Contains(y.Phonenumber2.ToPhoneNumber()))
.ToList();
}
// Extension method used
public static string ToPhoneNumber(this string phoneNumber)
{
if (phoneNumber == null || phoneNumber == string.Empty)
return string.Empty;
return phoneNumber.Replace("(", "").Replace(")", "")
.Replace(" ", "").Replace("-", "");
}
我可以使用什么数据结构来比较 Mobile 和 Telephone2 与 500 万个数字的列表以获得更好的性能?
【问题讨论】:
-
看
HashSet -
1) 尝试使用
HashSet<T>而不是List<T>2) 缓存ToPhoneNumber()结果,您对所有元素都调用了很多次。 -
-
您从哪里获得电话号码(GetAllNumbers 的内部信息)?为了快速获得它,理想的情况是源已经准备好进行此类操作,例如在那里有一个索引或类似的东西。
-
@RufusL:那不是字符串。包含,那是集合。包含。
标签: c# .net linq search optimization