使用LINQ条件的GroupBy和Count

时间:2016-11-13 05:55:23

标签: c# linq group-by

我有一个 Exam 表格,然后是 ExamResults ,其中包含特定考试的所有问题。此表将包含问题,选择的答案和AnswerPower,以指示答案是否正确:

  • 1 (表示正确),
  • 0 (表示错误),
  • NULL (表示没有回答,将被视为错误)。

我正在尝试按章节分组的特定考试的Count错误答案。

以下将给出按章分组的答案数,但我不知道确切地设定条件的位置只计算 错误答案 可以简单地AnswerPower!=1

                var query = ex.ExamResults
                .GroupBy(p => new
            {
                p.Question.Chapter.ChapterName,
                p.AnswerPower
            })
            .Select(g => new
            {
                g.Key.ChapterName,
                Mistakes = g.Count()
            });

2 个答案:

答案 0 :(得分:2)

count内你可以给出如下条件,请注意我已从AnswerPower

删除了GroupBy
  var query = ex.ExamResults
        .GroupBy(p => new
    {
        p.Question.Chapter.ChapterName
    })
    .Select(g => new
    {
        g.Key.ChapterName,
        Mistakes = g.Count(x => x.AnswerPower!=1),
        CorrectAnswers = g.Count(x => x.AnswerPower==1)
    });

答案 1 :(得分:1)

ex.ExamResults
   .GroupBy(p => new
            {
                p.Question.Chapter.ChapterName,
                p.AnswerPower
            })
    .Where(p => p.AnswerPower!=1)
    .Select(g => new
            {
                g.Key.ChapterName,
                Mistakes = g.Count()
            });
相关问题