当我运行以下代码(其中campaigns.Count()为200,000)时,该代码的运行速度确实很慢。
List<Campaign> listCampaigns = new List<Campaign>();
foreach (var item in campaigns)
{
if (listCampaigns.Where(a => a.CampaignName == item.CampaignName && a.Term == item.Term).Count() == 0)
{
//this doesn't exist
listCampaigns.Add(item);
}
else
{
//this exists already
var campaign = listCampaigns.Where(a => a.CampaignName == item.CampaignName && a.Term == item.Term).First();
campaign.TotalVisits += item.TotalVisits;
List<Conversion> listConversions = item.Conversions.ToList();
listConversions.AddRange(campaign.Conversions.ToList());
campaign.Conversions = listConversions.ToArray();
}
}
是否有必要优化此代码的一部分或使用另一种方法来加快速度?
任何建议表示赞赏。谢谢。
最佳答案
这应该快得多:
List<Campaign> listCampaigns = new List<Campaign>();
foreach (var g in campaigns.GroupBy(c => new { c.CampaignName, c.Term }))
{
var campaign = g.First();
campaign.TotalVisits = g.Sum(x => x.TotalVisits);
campaign.Conversions = g.SelectMany(c => c.Conversions).ToArray();
listCampaigns.Add(campaign);
}
关于c# - C#自定义组对于大型数据集非常慢,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5173871/