在我使用的 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();
这确实更快,但现在新查询返回的记录比第一个少。在我看来,这两段代码在做同样的事情,应该返回相同数量的记录。谁能看出他们为什么不这样做?我在这里缺少什么?
最佳答案
第一个查询可能会向列表中添加一个空对象(SingleOrDefault
将返回该类型的默认值,或者在这种情况下为 null
,如果它找不到匹配的实体)。因此,对于没有匹配关系的每个客户,您可以向该 List<>,
添加一个空对象。这会增加计数。
关于c# - 为什么这两个 linq 查询返回不同数量的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20060754/