views:

140

answers:

5

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 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();
+4  A: 

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(); 
Binary Worrier
+1  A: 

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

Marcelo Cantos
+7  A: 

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();
Jon Skeet
Perfect, thanks.
jamone
+1  A: 

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.

Kirk Broadhurst
+1  A: 

My best guess:

Count != Sum

You want the accumulated value of .Count?

Benjamin Podszun
Hrmpf.. 0 answers when I wrote this, "Are you a human being" vs. NoScript later: 6 identical answers.
Benjamin Podszun