omarmallat omarmallat - 26 days ago 10
C# Question

GroupBy and Count with condition using LINQ

I have an

Exam
table, and then
ExamResults
which includes all questions of a specific Exam. this table will contain the question, the answer selected, and the AnswerPower to indicate if the answer was correct or not:


  • 1 (means correct),

  • 0 (means wrong),

  • NULL (means not answered and will be considered as wrong).



I am trying to get the
Count
of wrong answers of a specific exam grouped by chapters.

The following will give me the count of answers grouped by chapter, but I don't know where exactly to set the condition to count only wrong answers which can be simply
AnswerPower!=1


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

Answer

Inside count you can give the condition like below, Note that I have removed AnswerPower from 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)
    });