很抱歉,如果已经在某个地方询问过,但我无法找到它。似乎Average和Sum在匿名类型中不起作用。我已经尝试了一段时间让这段代码工作,没有运气。我正在做的查询是:
var trainingPlan = (from tp in context.TPM_TRAININGPLAN
join tpd in context.TPM_TRAININGPLANDELIVERABLES on tp.TRAININGPLANID equals tpd.TRAININGPLANID
join t in context.TPM_TASK on tpd.TASKID equals t.TASKID
where tp.TPM_PROJECTVERSION.PROJECTID == projectId && tp.TPM_PROJECTVERSION.VERSIONID == versionId && tp.TRAININGPLANTYPE == "prescribed"
select new
{
CourseLength = tp.COURSELENGTHHOUR * 60 + tp.COURSELENGTHMINUTE,
DeliveryMethod = tp.TPM_DELIVERYMETHODS.NAME,
CourseCode = t.COURSECODE
});
我现在想要获取CourseLength属性的总和,所以我这样做:
int sum = trainingPlan.Sum(l => l.CourseLength.Value);
然而,“sum”最终为0.与“Average”相同。我可以在调试器下清楚地看到trainingPlan有两个项目,一个是CourseLength = 90,一个是CourseLength = 150。
Sum是否只适用于这些类型的枚举?谢谢!
答案 0 :(得分:3)
这肯定是数据库提供商的问题?由于这是一个小集合,你可以做trainingPlan.AsEnumerable()。总和。或者,如果您正在进行多次计算,请执行trainingPlan.ToList(),将其存储并在计算中使用它。
答案 1 :(得分:1)
这很好用:
class Program {
static void Main(string[] args) {
var stuff = from i in new double[] { 1, 2, 3 }
select new {
Value = (int) i,
};
var sum = stuff.Sum( s => s.Value);
Console.WriteLine(sum);
}
}
所以试试:
select new
{
CourseLength = (int) tp.COURSELENGTHHOUR * 60 + tp.COURSELENGTHMINUTE,
DeliveryMethod = tp.TPM_DELIVERYMETHODS.NAME,
CourseCode = t.COURSECODE
});
and int sum = trainingPlan.Sum(l => l.CourseLength);