C# 含前导零字符串属性的IEnumerable集合自定义排序实现
实现方案
核心排序逻辑分为两个优先级维度,按顺序执行即可匹配需求:
- 第一优先级:优先判断字符串小数点左侧部分是否为纯0组成,纯0前缀长度越长排序越靠前,优先级顺序为
000.>00.>0.,所有非纯0开头的内容统一排在这三类之后 - 第二优先级:相同前缀优先级的内容,按字符串对应的十进制数值升序排列
代码实现
// 基础实现(适用age格式统一为「数字.数字」规范的场景) var sortedItems = items.OrderBy(x => { var leftPart = x.age.Split('.')[0]; // 纯0前缀用负长度做升序,实现长前缀靠前的效果 return leftPart.All(c => c == '0') ? -leftPart.Length : 0; }) .ThenBy(x => decimal.Parse(x.age)) .ToList();
鲁棒性优化版本
如果存在格式不规范的age字段,可增加校验避免运行时报错:
var sortedItems = items.OrderBy(x => { if (string.IsNullOrWhiteSpace(x.age)) return int.MaxValue; var leftPart = x.age.Split('.').FirstOrDefault() ?? string.Empty; return leftPart.All(c => c == '0') ? -leftPart.Length : 0; }) .ThenBy(x => { decimal.TryParse(x.age, out var num); return num; }) .ToList();
效果验证
用你提供的测试用例运行后,输出结果为:["000.1", "00.2", "00.5", "0.1", "0.3", "0.4", "1.2", "2.1"]
完全匹配预期排序要求。
内容的提问来源于stack exchange,提问作者Emily MM
相关产品推荐
相关产品推荐

