【发布时间】:2013-11-19 00:22:53
【问题描述】:
在我使用的一个 Web 应用程序中,我发现了一段很慢的代码,我想加快速度。原代码如下:
foreach (Guid g in SecondaryCustomersIds)
{
var Customer = (from d in Db.CustomerRelationships
join c in Db.Customers on
d.PrimaryCustomerId equals c.CustomerId
where c.IsPrimary == true && d.SecondaryCustomerId == g
select c).Distinct().SingleOrDefault();
//Add this customer to a List<>
}
我认为将这些全部加载到单个查询中可能会更快,因此我尝试将其重写为以下查询:
var Customers = (from d in Db.CustomerRelationships
join c in Db.Customers on
d.PrimaryCustomerId equals c.CustomerId
where c.IsPrimary == true && SecondaryCustomersIds.Contains(d.SecondaryCustomerId)
select c).Distinct();
这确实更快,但现在新查询返回的记录比第一个要少。在我看来,这两个代码块正在做同样的事情,并且应该返回相同数量的记录。谁能明白他们为什么不这样做?我在这里错过了什么?
【问题讨论】:
-
可能是您在第一个中有重复项?您是否尝试过在添加所有客户的最终列表中添加
.Distinct? -
不,对不起,我应该提到这一点。获取最终列表的不同值会返回相同的计数,因此不会返回重复项。
-
SecondaryCustomersIds是如何定义的? -
这是一个
List<Guid>,使用可能超出此问题范围的方法填充。我可以说两段代码都使用了相同的SecondaryCustomersIds。 -
这里的基准测试怎么样?它会给你答案,但可能无法解释原因。
标签: c# .net performance linq