如果我从查询中选择匿名类型(select new
):
var smsPerGroup = from g in db.Groups
select new
{
GroupName = g.Name,
ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count()
};
发生的事情是我无法对它进行求和(
)int max = smsPerGroup.Max(g => g.ReceivedSMS); // ERROR!
抛出的错误是:
There was an error parsing the query.
对此最正确的解决方案是什么?
我不希望在此查询中创建一个只能使用一次的类。
是否可以使用“非常匿名”类型?这是:定义其属性的类型,而不是类本身的类型
这样的事情:(在语法上不正确)
...
select new
{
string GroupName = g.Name,
int ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count()
};
编辑:错误详情如下
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);
答案 0 :(得分:3)
一个简单的解决方案是在调用.Sum()之前使用.ToList()实现查询:
var test = (from g in db.Groups
select new
{
GroupName = g.Name,
ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count()
}).ToList();
var sum = test.Sum(t => t.ReceivedSMS);