在linq中分组和平均

时间:2011-06-05 18:54:08

标签: c# .net linq ado.net linq-to-entities

我有2张桌子。 MarkQuestion和Question。

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 = ..
                          };

如何解决这个问题?

2 个答案:

答案 0 :(得分:9)

听起来我想要一个群组加入,这样你就有两个范围变量 - 一个代表一个问题,另一个代表该特定问题的所有标记问题。

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

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方法获得相同的结果。

答案 1 :(得分:1)

这样的事情:

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