gpt4 book ai didi

c# - LINQ 按 ParentId 分组

转载 作者:行者123 更新时间:2023-12-02 21:59:16 26 4
gpt4 key购买 nike

我有一个看似简单的任务,但我遇到的麻烦远比我愿意承认的要多。我有一个层次表,我需要查询和显示由父级和相关子级分组的结果。

我当前的 LINQ 查询:

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

这会产生一个结果集:

enter image description here

我要制作的是:

enter image description here

我的问题很简单,如何使用 Lambda 语法获得所需的结果。

最佳答案

根据 Servys 的评论更新。

第一行是确保将所有相关问题组合在一起。第二行是确保父问题在第一位。第三行是正确排序

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

关于c# - LINQ 按 ParentId 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17220032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com