简体   繁体   English

为什么这两个linq查询返回不同数量的结果?

[英]Why do these two linq queries return different numbers of results?

In a web application that I work with I found a slow piece of code that I wanted to speed up a bit. 在与我一起使用的Web应用程序中,我发现了一段很慢的代码,想加快一点速度。 Original code below: 原始代码如下:

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<>
}

I thought it might be faster to load this all into a single query, so I attempted to rewrite it as the query below: 我认为将所有内容加载到单个查询中可能会更快,因此我尝试将其重写为以下查询:

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();

Which is indeed faster, but now the new query returns fewer records than the first. 这确实更快,但是现在新查询返回的记录少于第一个。 It seems to me that these two chunks of code are doing the same thing and should return the same number of records. 在我看来,这两个代码块在做相同的事情,应该返回相同数量的记录。 Can anyone see why they would not? 谁能看到他们为什么不这样做? What am I missing here? 我在这里想念什么?

It's possible for the first query to add a null object to the list ( SingleOrDefault will return the default for the type, or null in this case, if it can't find a matching entity). 第一个查询有可能向列表中添加一个空对象( SingleOrDefault将返回该类型的默认null ,如果找不到匹配的实体,则返回null )。 Thus, for every Customer without a matching relationship, you could be adding a null object to that List<>, which would increase the count. 因此,对于每个没有匹配关系的客户,您都可以向该List<>,添加一个空对象List<>,这将增加计数。

In your first scenario, does your final List<Customers> have duplicates? 在第一种情况下,最终的List<Customers>是否重复?

You're calling Distinct , but also looping, which means you're not doing Distinct on your entire collection. 您在调用Distinct ,但也在循环,这意味着您没有对整个集合执行Distinct

Your second example is calling Distinct on the entire collection. 您的第二个示例是在整个集合上调用Distinct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM