C# LINQ:按双层嵌套属性排序Wrapper集合的技术需求
问题描述
给定以下C#类:
public class SecondNestingLevel { public string SortProperty {get; set;} // 修正原代码拼写错误:SortPropety → SortProperty } public class FirstNestingLevel { public ICollection<SecondNestingLevel> SecondNestingLevelCollection {get; set;} } public class Wrapper { public ICollection<FirstNestingLevel> FirstNestingLevelCollection {get; set;} }
需要对Wrapper对象的集合按以下规则排序:
- 第一部分:所有内部全部
SecondNestingLevel的SortProperty值完全相同的Wrapper对象,按该统一值的字母顺序排序; - 第二部分:剩余的
Wrapper对象,按其嵌套集合中**第一个FirstNestingLevel下的第一个有效SecondNestingLevel的SortProperty**字母顺序排序。
解决方案
核心逻辑
先为每个Wrapper计算两个关键标记:
IsUniform:标记该对象内部所有非空SortProperty是否完全一致;SortKey:如果IsUniform为true,取这个统一的SortProperty值;否则取第一个有效SortProperty值。
排序时先按IsUniform降序(让统一值的组排在前面),再按SortKey的字母顺序升序。
代码实现
using System.Linq; // 封装排序信息的扩展方法 public static class WrapperSortExtensions { public static (bool IsUniform, string SortKey) GetSortInfo(this Wrapper wrapper) { // 提取所有非空的SortProperty值,避免空引用 var allValidSortProps = wrapper.FirstNestingLevelCollection? .SelectMany(firstLevel => firstLevel.SecondNestingLevelCollection? .Select(secondLevel => secondLevel.SortProperty) .Where(prop => !string.IsNullOrEmpty(prop))) .ToList(); // 处理无有效属性的边界情况 if (allValidSortProps?.Any() != true) { return (false, string.Empty); } // 判断所有属性值是否一致 bool isUniform = allValidSortProps.Distinct().Count() == 1; string sortKey = isUniform ? allValidSortProps.First() : allValidSortProps.First(); return (isUniform, sortKey); } } // 排序调用示例 public static class WrapperSorter { public static IEnumerable<Wrapper> SortWrappers(IEnumerable<Wrapper> wrapperList) { return wrapperList .OrderByDescending(w => w.GetSortInfo().IsUniform) .ThenBy(w => w.GetSortInfo().SortKey); } }
代码说明
- 扩展方法
GetSortInfo统一处理了嵌套集合的遍历、空值过滤和一致性判断,避免重复逻辑; - 排序时通过
OrderByDescending确保统一值的Wrapper排在前面,再用ThenBy完成字母序排序; - 兼容了嵌套集合为空、
SortProperty为空的边界场景,避免空引用异常。
内容的提问来源于stack exchange,提问作者Krisuuuuuu
相关产品推荐
相关产品推荐

