You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中实现列表的字母与数字混合自然排序?

解决方案

针对混合纯字母和「前缀+数字」格式的商品排序需求,你可以通过以下两种方式解决原代码的索引越界问题,同时实现自然排序:

方案一:正则表达式匹配(推荐,适配更复杂的命名格式)

通过正则精准提取商品名的字母前缀和数字后缀,避免空格分割带来的异常:

using System.Text.RegularExpressions;

// 预编译正则,匹配字母前缀 + 可选的数字后缀(支持前缀与数字间任意空格)
var namePattern = new Regex(@"^([A-Za-z]+)\s*(\d+)?$", RegexOptions.Compiled);

var orderedProducts = DisplayProducts
    .Select(item => new 
    {
        Original = item,
        MatchResult = namePattern.Match(item.Product.ProductName)
    })
    .Select(temp => new 
    {
        Original = temp.Original,
        Prefix = temp.MatchResult.Groups[1].Value,
        // 纯字母商品设置为极大值,确保同前缀下排在带数字商品之后
        SuffixNumber = temp.MatchResult.Groups[2].Success ? int.Parse(temp.MatchResult.Groups[2].Value) : int.MaxValue
    })
    .OrderBy(temp => temp.Prefix)
    .ThenBy(temp => temp.SuffixNumber)
    .Select(temp => temp.Original)
    .ToList();

说明:

  • 正则^([A-Za-z]+)\s*(\d+)?$会匹配两种格式:
    1. 纯字母商品(如BOAT):仅捕获字母前缀,数字分组为空
    2. 前缀+数字商品(如TERRAIN 12):捕获字母前缀和数字后缀,支持前缀与数字间的多空格
  • 纯字母商品的SuffixNumber设为int.MaxValue,保证同前缀下(若存在)会排在所有带数字的同前缀商品之后;不同前缀的纯字母商品仍按字母顺序排序

方案二:空格分割+安全解析(适合格式规范的场景)

如果商品名格式是严格的「前缀+单个空格+数字」,可以改进原有的Split逻辑,避免索引越界:

var orderedProducts = DisplayProducts
    .Select(item => new 
    {
        Original = item,
        NameParts = item.Product.ProductName.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
    })
    .Select(temp => new 
    {
        Original = temp.Original,
        Prefix = temp.NameParts[0],
        // 仅当分割后有第二部分且能解析为数字时才赋值,否则用极大值
        SuffixNumber = temp.NameParts.Length > 1 && int.TryParse(temp.NameParts[1], out var num) ? num : int.MaxValue
    })
    .OrderBy(temp => temp.Prefix)
    .ThenBy(temp => temp.SuffixNumber)
    .Select(temp => temp.Original)
    .ToList();

说明:

  • 使用StringSplitOptions.RemoveEmptyEntries移除分割产生的空元素,避免多空格导致的无效条目
  • 通过int.TryParse安全解析数字,同时判断分割后的数组长度,彻底避免索引越界报错

内容的提问来源于stack exchange,提问作者hagru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:10:33