If I select an anonymous type (select new
) from a query:
var smsPerGroup = from g in db.Groups
select new
{
GroupName = g.Name,
ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count()
};
It happends that I can't sum() on it:
int max = smsPerGroup.Max(g => g.ReceivedSMS); // ERROR!
The error thrown is:
There was an error parsing the query.
What is the most correct solution for this?
I don't want to create a class to use ONLY one time, on this query.
Is it possible to have a "not very anonymous" type? this is: to define the type of its properties but not the type of the class itself
Something like this: (which is syntactically incorrect)
...
select new
{
string GroupName = g.Name,
int ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count()
};
Edit: the error in detail is the following
There was an error parsing the query. [ Token line number = 6,Token line offset = 5,Token in error = SELECT ]
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlServerCe.SqlCeException: There was an error parsing the query. [ Token line number = 6,Token line offset = 5,Token in error = SELECT ]
Source Error:
Line 159: };
Line 160:
Line 161: int max = smsPerGroup.Max(g => g.ReceivedSMS);
A simple solution would be to materialize the query with .ToList() before calling .Sum():