我有一个场景,我需要根据另一个列表中的数据更新几个项目。我已经在这里解决了各种问题,但没有任何帮助。
设想
listA:总计数约为 88000
public class CDRs
{
public string cld { get; set; }
public string prefix2 { get; set; }
public string country { get; set; }
public string city { get; set; }
}
listB:总计数:3000。
public class RatesVM
{
public string prefix { get; set; }
public string Country { get; set; }
public string City { get; set; }
}
现在,在数组listB可以有多个匹配listA的字段是CLD
例如。listA.cld = "8801123232"; 我从 ListB 得到的匹配前缀是
880 BGD Proper
8801 BGD Mobile
88011 BGD Dhaka Mobile
88017 BGD Dhaka Mobile
88018 BGD Dhaka Mobile
88019 BGD Dhaka Mobile
现在我想要在这种情况下最接近的匹配
88011 BGD Dhaka Mobile
我现在正在遵循的方法。
foreach (var x in listA)
{
var tempObj = listB.FirstOrDefault(y => x.cld.StartsWith(y.prefix));
if (tempObj != null)
{
x.prefix2 = tempObj.prefix;
x.country = tempObj.Country;
x.city = tempObj.City;
}
else
{
x.prefix2 = "InBound";
x.country = "Unknown";
x.city = "Unknown";
}
}
它工作正常,但需要很多时间。对于这种情况,大约需要 2-3 分钟。
很少有情况下 ListA 会有大约 100 万条记录。我担心它会永远持续下去。
提前谢谢了
我会建议下面的代码。关键的区别在于使用orderedListB
以确保您获得最具体的匹配(即首先从最长的前缀开始),以及Dictionary
缓存结果。*
Dictionary<string, RatesVM> cache = new Dictionary<string, RatesVM>();
var orderedListB = listB.OrderByDescending(z => z.prefix.Length).ToList();
foreach (var x in listA)
{
RatesVM cached;
cache.TryGetValue(x.cld, out cached);
var tempObj = cached ?? orderedListB.FirstOrDefault(z => x.cld.StartsWith(z.prefix));
if (tempObj != null)
{
if (cached == null)
{
cache.Add(x.cld, tempObj);
}
x.prefix2 = tempObj.prefix;
x.country = tempObj.Country;
x.city = tempObj.City;
}
else
{
x.prefix2 = "InBound";
x.country = "Unknown";
x.city = "Unknown";
}
}
您可能还想考虑使用Parallel.ForEach
而不仅仅是 foreach。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句