Mike Ramsey
Mike Ramsey

Reputation: 843

LINQ Grouping by ParentId

I have a seemingly simple task that I am having far more trouble than I care to admit doing. I have a hierarchical table that I need to query and display the results grouped by the parent with associated children.

My current LINQ query:

var quests = Questions.Include(q => q.Question2)
      .Include(q => q.Sections)
      .Include(q => q.QuestionType)
      .Include(q => q.AnswerOptions)
      .Where(sq => sq.Sections.Any(s => s.SectionId == sectionId))
      .OrderBy(q=> q.QuestionId).ThenBy(q => q.ParentQuestionId);

This produces a result set of:

enter image description here

What I want to produce is:

enter image description here

My Question is simply, how can I get the desired results using Lambda syntax.

Upvotes: 2

Views: 1338

Answers (3)

Servy
Servy

Reputation: 203829

So it seems what you're really trying to create here is a tree based structure in which, at the top level, you have all questions with no parent, and then as "child" nodes all questions that have that as a parent.

var questions = GetAllQuestions();//here is where you can put your includes, etc.

var query = questions.Where(q => q.ParentQuestionId != null)
    .GroupBy(q => q.ParentQuestionId)
    .Select(group => new
    {
        Parent = questions.First(q => q.QuestionId == group.Key),
        Children = group.OrderBy(q => q.DisplayOrder),
    })
    .OrderBy(group => group.Parent.DisplayOrder);

Upvotes: 3

Aducci
Aducci

Reputation: 26644

Update based on Servys' comment.

First line is to make sure all related questions are grouped together. Second line is to make sure parent question is first. Third line is to order properly

 .OrderBy(q => q.ParentQuestionId == null ? q.QuestionId : q.ParentQuestionId)
 .ThenBy(q => q.ParentQuestionId == null ? 0 : 1)
 .ThenBy(q => q.DisplayOrder);

Upvotes: 4

matt-dot-net
matt-dot-net

Reputation: 4244

.OrderBy(x => (x.ParentQuestionId==null?x.QuestionId:x.ParentQuestionId.Value));

Upvotes: -1

Related Questions