多次C#linq组

时间:2016-02-21 10:32:30

标签: c# linq group-by

我有一个对象测验,看起来像:

public class Quiz
{     
    public int Id { get; set; }          
    public ICollection<MathQuiz> MathQuizzes { get; set; }     
}

MathQuizze对象如下所示:

public class MathQuiz
{

    public int Id { get; set; }

    public int QuizId{ get; set; }
    public Quiz Quiz{ get; set; }

    public int AnswerId { get; set; }
    public Answer Answer { get; set; }

    public int TagId{ get; set; }
    public Tag Tag { get; set; }

    public bool IsCorrect { get; set; }

}

有一个对象(UserQuizzes)看起来像:

public class UserQuizes
    {
        public int Id { get; set; }


        public int UserId { get; set; }
        public User User { get; set; }


        public int QuizId { get; set; }
        public Quiz Quiz { get; set; }

}

UserQuizzes只是表达用户和测验之间多对多关系的类。 这是一个示例数据:

     List<Quiz> quizzes = new List<Quiz>();
        quizzes.Add(new Quiz{ Id = 1, MathQuizzes = new List<MathQuiz>{ 
                  new MathQuiz { AnswerId = 58, TagId = 1, IsCorrect = false },  
                  new MathQuiz { AnswerId = 26, TagId = 2, IsCorrect = true }, 
                  new MathQuiz { AnswerId = 57, TagId = 3, IsCorrect = true },

                  new Quiz{ Id = 2, MathQuizzes = new List<MathQuiz>{ 
                  new MathQuiz { AnswerId = 59, TagId = 1, IsCorrect = false },  
                  new MathQuiz { AnswerId = 87, TagId = 2, IsCorrect = true }, 
                  new MathQuiz { AnswerId = 25, TagId = 3, IsCorrect = true }, });

    List<UserQuizzes> userQuizzes = new List<UserQuizzes>();
        userQuizzes.Add(new Quiz{ QuizId = 1, UserId = 1},
        userQuizzes.Add(new Quiz{ QuizId = 2, UserId = 1});

请不要花太多时间批评,我只想使用每个人都非常熟悉的东西。

我想要实现的是用户按照MathQuiz TagId进行分组并得到如下数据:

TagId : 1, IsCorrect: true(0), false(2);
TagId : 2, IsCorrect: true(2), false(0);
TagId : 3, IsCorrect: true(2), false(0);

1 个答案:

答案 0 :(得分:1)

您发布的代码有拼写错误,但这是基本想法:

var query =
    from q in quizzes
    from mq in q.MathQuizzes
    join uq in userQuizzes on q.Id equals uq.QuizId
    group mq by mq.TagId into g
    select new
    {
        TagId = g.Key,
        Correct = g.Sum(e => e.IsCorrect ? 1 : 0),
        Incorrect = g.Sum(e => e.IsCorrect ? 0 : 1)
    };

基本上,你需要通过加入数据集来获得有效的源集,并进行常规的分组/计算聚合。