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

时间:2021-07-10 11:10:42

Crazy question...however, I want the sum of all the rows in a table for a column (without using the group by clause)

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

Example:

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

I want the sums for each column.

我想要每列的总和。

Final results should look like:

最终结果应如下所示:

Answer1Sum  Answer2Sum  Answer2Sum

8           7           8

This doesn't work:

这不起作用:

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

3 个解决方案

#1


Would this work:

这会工作:

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

#2


A VB.NET soltuion to this answer for anyone that needs it is as follows:

对于需要它的任何人来说,这个答案的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)

#3


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

#1


Would this work:

这会工作:

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

#2


A VB.NET soltuion to this answer for anyone that needs it is as follows:

对于需要它的任何人来说,这个答案的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)

#3


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