LINQ |如何在没有分组的情况下获得SUM?

时间:2009-07-01 20:49:37

标签: linq linq-to-entities aggregate sum aggregation

疯狂的问题......但是,我想要一个表中所有行的总和(不使用group by子句)

示例:

Table = Survey
Columns = Answer1, Answer2, Answer3
        1        1         1
        4        3         5
        3        3         2

我想要每列的总和。

最终结果应如下所示:

Answer1Sum  Answer2Sum  Answer2Sum

8           7           8

这不起作用:

from survey in SurveyAnswers
select new
{
    Answer1Sum = survey.Sum(),
    Answer2Sum = survey.Sum(),
    Answer3Sum = survey.Sum()
 }

3 个答案:

答案 0 :(得分:8)

这会有效吗?

var answer1Sum = SurveyAnswers.Sum( survey => survey.Answer1 );
var answer2Sum = SurveyAnswers.Sum( survey => survey.Answer2 );
var answer3Sum = SurveyAnswers.Sum( survey => survey.Answer3 );

答案 1 :(得分:1)

对于需要它的任何人来说,这个答案的VB.NET解决方案如下:

Dim Answer1Sum = SurveyAnswers.Sum(Function(survey) survey.Answer1)
Dim Answer2Sum = SurveyAnswers.Sum(Function(survey) survey.Answer2)
Dim Answer3Sum = SurveyAnswers.Sum(Function(survey) survey.Answer3)

答案 2 :(得分:0)

SurveyAnswers.Sum(r => r.Answer1);