[英]Can someone explain why these two linq queries return different results?
[英]Why do these two linq queries return different numbers of results?
在与我一起使用的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
,如果找不到匹配的实体,则返回null
)。 因此,对于每个没有匹配关系的客户,您都可以向该List<>,
添加一个空对象List<>,
这将增加计数。
在第一种情况下,最终的List<Customers>
是否重复?
您在调用Distinct
,但也在循环,这意味着您没有对整个集合执行Distinct
。
您的第二个示例是在整个集合上调用Distinct
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.