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

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);

最佳答案

您发布的代码有错别字,但这是基本思想:

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)
    };


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

关于c# - C#LINQ组被多次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35534998/

10-11 12:27