Daniel Breen14,637 Points
Select vs SelectMany When Getting Average
With the following code in mind...
var sightingsCorrect = birds.SelectMany(b => b.Sightings).Count(); // 1817 var sightingsWrong = birds.Select(b => b.Sightings).Count(); // 201 var average = birds.Select(b => b.Sightings.Count()).Average(); // 9.03980099502488
sightingsCorrect uses SelectMany(), while
sightingsWrong and average use Select().
Why don't we use SelectMany to get the average? How does Linq bring back the correct average? I would assume that
average would be 1 (201 / 201 = 1)
Steven Parker195,142 Points
These variable names are a bit confusing, "sightingsCorrect" is actually the total number of sightings, and "sightingsWrong " is just a count of birds. It could be written more simply without the "Select" as:
var sightingsWrong = birds.Count(); // 201
The reason the average works is that the "Count" is applied to the sightings for each bird. So the "Average" totals them up and then divides by the number of counts. You can't use "SelectMany" there because it works on lists, not individual values as the "Count" returns.