Take the following linq query:
var summary = results.Select(r =>
new
{
TotalPopulation = results.Sum(s => s.Population),
TotalGross = results.Sum(s => s.Gross),
}).Distinct();
The above works fine, but is it the best way to do it. What does the r represent? Why do I need it?
Also, I would think that I could add the following to my query, but I can’t:
GrossPerPop = TotalPopulation / TotalGross
The above says TotalPopulation and Total Gross do not exist in the current context.
I also tried:
GrossPerPop = results.sum(s => s.Population) / results.Sum(s => s.Gross),
The above says / can’t be applied to decimal? or double? Does this have anything to do with the fields being nullable? It just so happens I don’t have any Population fields or Gross fields with a null value, so I changed these to non-nullable fields in the sql table designer. However, if they do contain a 0 value, how could I check that within the Linq code?
A better way is something like:
Then:
What you currently have is performing the above projection (albeit into an anonymous type) for every element of
resultsand then throwing out all but one of the resulting projections. You could get by without creating an explicit type as I’ve done above and just use an anonymous type but that would be silly.The
rrepresents the name of the parameter in the anonymous method that you’ve defined.When you write
it is necessary that
expressionbe a delegate that eats whatever the type of the elements ofresultsare and returns some other type. That isIEnumerable<SomeType>.Selectis for projecting a sequenece to another sequence. Therefore, you must pass a method that eats whatever the type of the elements ofresultsare and returns some other type. One way of doing is that is by passing in an anonymous delegate. One way of defining an anonymous delegate is by using a lambda expression. When you sayr => ...you are defining an anonymous method via a lambda expression.That’s right, you can’t. Think of it like this. Say that you had an explicit type
Should the following be legal?
Of course not! But that’s effectively what you are trying to do.
I don’t see any reason for you to be getting such a message. In C#, the above is legal assuming that both
s.Populationands.Grossare numeric types; they will just be implicitly promoted to the "right" type. This is true even ifs.Populationors.Grossare numeric types.Do note however that gross per population should be