分组并按林求平均值



我有两个表。标记问题和问题。

MarkQuestion has:
IDQuestion,
IDUser,
Mark
Question has:
IDQuestion,
Text

我想提取每个问题的文本和每个问题的平均分数:

我试过这样的东西:

var questions = from mark in Entities.MarkedQuestions
                          join question in Entities.Questions on mark.IDQuestion equals question.IDQuestion
                          group mark by mark.IDQuestion into markGroup,
                          question by question.IDQuestion into questionGroup
                          select new ModelView.MarkQuestionModel
                          {
                              AverageMark = markGroup.Average(x => x.Mark),
                              Text = ..
                          };

如何解决这个问题?

在我看来,你想要一个组联接,这样你就有了两个范围变量——一个代表一个问题,另一个代表该特定问题的所有标记问题。

以下是您要使用的查询表达式语法:

var questions = from question in Entities.Questions
                join marked in Entities.MarkedQuestions
                    on question.IDQuestion equals marked.IDQuestion
                    into marks
                select new ModelView.MarkQuestionModel
                {
                    AverageMark = marks.Average(x => x.Mark),
                    Text = question.Text
                };

对于点表示法,您可以使用GroupJoin方法来获得相同的结果。

类似这样的东西:

var questions =
    from question in Entities.Questions 
    select
        new
        {
            question.Text,
            AverageMark = Entities.MarkedQuestions
                .Where(arg => arg.IDQuestion == question.IDQuestion)
                .Average(arg => arg.Mark)
        };

相关内容

  • 没有找到相关文章

最新更新