如何在C#中让分组与非分组列表项处于同一层级?
解决方案
基础实现(匹配你的示例需求)
你的核心需求是将两类数据并列:Parent为null的单个项,以及按非null Parent分组的子项集合。直接按Parent分组会把所有null项归为一组,不符合要求,所以我们可以拆分处理后再合并:
// 1. 提取所有Parent为null的项,投影成目标结构 var standaloneItems = tempResult .Where(r => r.Parent == null) .Select(r => new { id = r.Id, itemDescription = r.ItemDescription, commonDescription = r.CommonDescription }); // 2. 对Parent非null的项按Parent分组,生成带Children的组结构 var groupedChildItems = tempResult .Where(r => r.Parent != null) .GroupBy(r => r.Parent) .Select(g => new { Parent = g.Key, Children = g.Select(child => new { id = child.Id, itemDescription = child.ItemDescription, commonDescription = child.CommonDescription }) }); // 3. 合并两部分得到最终结果 var finalResult = standaloneItems.Concat(groupedChildItems).ToList();
更全面的场景处理(如果存在「自身是父项的Parent=null项」)
如果你的数据中存在Parent为null且拥有子项的项(比如某个Id=3的项Parent为null,同时有其他项的Parent=3),你可能希望把这类项直接带上Children,而不是单独存在再额外生成一个Parent=3的组。这种情况需要先识别所有父Id集合,再分三类处理:
// 先获取所有存在子项的父Id集合 var existingParentIds = tempResult .Where(r => r.Parent != null) .Select(r => r.Parent) .Distinct() .ToList(); // 1. 无子女的Parent=null项 var standaloneParentNull = tempResult .Where(r => r.Parent == null && !existingParentIds.Contains(r.Id)) .Select(r => new { id = r.Id, itemDescription = r.ItemDescription, commonDescription = r.CommonDescription }); // 2. 有子女的Parent=null项(自身作为父节点) var parentWithChildren = tempResult .Where(r => r.Parent == null && existingParentIds.Contains(r.Id)) .Select(r => new { id = r.Id, itemDescription = r.ItemDescription, commonDescription = r.CommonDescription, Children = tempResult .Where(child => child.Parent == r.Id) .Select(child => new { id = child.Id, itemDescription = child.ItemDescription, commonDescription = child.CommonDescription }) }); // 3. 不存在对应父项的子项分组(比如Parent=3但数据库中无Id=3的项) var orphanedGroups = existingParentIds .Where(pId => !tempResult.Any(r => r.Id == pId)) .Select(pId => new { Parent = pId, Children = tempResult .Where(child => child.Parent == pId) .Select(child => new { id = child.Id, itemDescription = child.ItemDescription, commonDescription = child.CommonDescription }) }); // 合并所有结果 var finalResult = standaloneParentNull .Concat(parentWithChildren) .Concat(orphanedGroups) .ToList();
关键说明
- 拆分处理避免了
GroupBy对null值的统一分组问题; - 使用匿名类投影可以精准匹配你需要的JSON结构,无需修改原
Response类; - 全面场景的处理覆盖了「父项存在」和「父项不存在」两种子项分组情况。
内容的提问来源于stack exchange,提问作者Tufan Chand
相关产品推荐
相关产品推荐

