jamone
jamone

Reputation: 17419

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

Upvotes: 1

Views: 234

Answers (5)

Benjamin Podszun
Benjamin Podszun

Reputation: 9837

My best guess:

Count != Sum

You want the accumulated value of .Count?

Upvotes: 1

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28738

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503290

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

Upvotes: 7

Marcelo Cantos
Marcelo Cantos

Reputation: 186078

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

Upvotes: 1

Binary Worrier
Binary Worrier

Reputation: 51719

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

Upvotes: 4

Related Questions