LINQ group by null问题

时间:2018-03-17 19:10:56

标签: linq entity-framework-core

我正在研究LINQ查询,在那里我需要所有问题,其中每个问题可能有或没有子问题。

我正在通过null / exception问题获得分组,因为一些父问题没有子问题。我正在做左连接;按父母问题分组

(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
                   join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
                   from childQuestion in qs.DefaultIfEmpty()
                   group childQuestion by question into g
                   select new
                   {
                       g.Key,
                       g
                   }).ToList();

2 个答案:

答案 0 :(得分:1)

找到了答案

(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
                   join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
                   from childQuestion in qs.DefaultIfEmpty()
                   group childQuestion by question into groupQuestions
                   select new
                   {
                       groupQuestions.Key,
                       childQuestions = groupQuestions.DefaultIfEmpty() == null? null : groupQuestions
                   }).ToList();

答案 1 :(得分:0)

如果您想要与他们的子问题相关的问题" cnsider使用GroupJoin?而不是内部联接,后跟GroupBy

小步骤:

IQueryable<Question> questions = dbContext.Questions.Where(...)
IQueryable<QuestinoHierarch> subQuestions = Context.QuestionHierarchy;

var questionsWithTheirSubQuestions = questions.GroupJoin(  // GroupJoin the questions
    subQuestions,                                          // with the subQuestions
    question => question.Id,           // from every question take the Id
    subQuestion => subQuestion.ParentQuestionId, 
                                       // from every subQuestion take the ParentQuestionId,
    (question, subQuestions) => new    // take the question with all matching subQuestions
    {                                  // to make one new object:
        // select only the question items you plan to use
        Title = question.Title,
        Priority = question.Priority,
        ...

        // select only the subQuestions that you want (or all)
        // for example only the answered sub questions:
        SubQuestions = subQuestions
             .Where(subQuestion.Type = QuestionType.Answered)
             .Select(subQuestion => new
             {
                  // again: select only the subQuestion properties you plan to use
                  Name = subQuestion.Name,
                  Date = subQuestion.Date,
                  ...
             })
             .ToList(),
    });

TODO:如果需要,请发表一个重要声明。