开发者

What is the difference between these two LINQ statements?

I had the 1nd statement in my code and found it not giving an accurate count, it was returning 1 when the correct answer is 18. To try and debug the problem I broke it out creating the 2nd statement here and the count returns 18. I just don't see what the difference is between these two. It seems like the 1st is just more compact.

I'm currently running these two statements back to back and I'm sure that the database isn't changing between开发者_StackOverflow社区 the two.

int count = (from s in surveysThisQuarter
             where s.FacilityID == facility.LocationID
             select s.Deficiencies).Count();

vs

 var tempSurveys = from s in surveysThisQuarter
                   where s.FacilityID == facility.LocationID
                   select s;
 int count = 0;
 foreach (Survey s in tempSurveys)
     count += s.Deficiencies.Count();


In the first query, you're selecting a bunch of "sets of deficiencies" and counting how many integers you've got. You want to sum them instead, by the sounds of it:

int count = (from s in surveysThisQuarter
             where s.FacilityID == facility.LocationID
             select s.Deficiencies.Count()).Sum();

or (may generate better SQL, who knows)

int count = (from s in surveysThisQuarter
             where s.FacilityID == facility.LocationID
             from x in s.Deficiencies
             select x).Count();


Thats because the second snippet is summing the Deficiencies count, while the first is counting the deficiencies.
This is the same as your second snippet

int count = (from s in surveysThisQuarter 
             where s.FacilityID == facility.LocationID 
             select s.Deficiencies.Count()).Sum(); 


The first form is counting the number of matching rows. You should use the Sum extension method instead.


The first is is returning a Count on an IEnumerable<Deficiencies> (or whatever type Deficiencies is). The result will be the same as surveysThisQuarter.Count(). This is because the result is actually a collection of collections.

The second is counting all the Deficiencies - which is probably what you want.

For the first work properly you'd need to SelectMany rather than Select, to flatten your collection.


My best guess:

Count != Sum

You want the accumulated value of .Count?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜