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

如何对List<T>多属性排序?实现Col3先按数值再按字母的自然排序

解决方案

要实现Col3按数值逻辑排序(纯数字按数值、带前缀字符串按前缀+数值排序),需要自定义排序规则,提取Col3中的前缀和数字部分作为排序键。

步骤1:编写辅助解析方法

创建一个方法从Col3中提取前缀和数字,生成排序所需的键:

private (string Prefix, int Number) GetCol3SortKey(string col3)
{
    // 提取字符串中的所有数字字符并转换为整数
    var numberStr = new string(col3.Where(char.IsDigit).ToArray());
    int number = int.TryParse(numberStr, out var parsedNum) ? parsedNum : 0;
    
    // 提取字符串中的非数字前缀部分
    var prefix = new string(col3.Where(c => !char.IsDigit(c)).ToArray());
    
    return (prefix, number);
}

步骤2:修改排序代码

使用上述方法生成的排序键进行排序,确保先按前缀(纯数字无前缀,会排在带前缀的条目之前),再按数值大小排序:

var orderedCustomers = Object
    .OrderBy(c => c.Col1)
    .ThenBy(c => c.Col2)
    .ThenBy(d => GetCol3SortKey(d.Col3).Prefix)
    .ThenBy(d => GetCol3SortKey(d.Col3).Number);

如果想提升效率(避免重复调用解析方法),可以先投影包含排序键的中间对象,再排序:

var orderedCustomers = Object
    .Select(c => new 
    {
        Item = c,
        SortKey = GetCol3SortKey(c.Col3)
    })
    .OrderBy(x => x.Item.Col1)
    .ThenBy(x => x.Item.Col2)
    .ThenBy(x => x.SortKey.Prefix)
    .ThenBy(x => x.SortKey.Number)
    .Select(x => x.Item);

效果说明

  • 纯数字的Col3值(如"1""2""10")会按数值升序排列,得到1,2,3,10,11,12的顺序
  • 带前缀的Col3值(如"P1""P2""P10")会先按前缀分组,再按后面的数值升序排列,得到P1,P2,P3,P10,P11,P12的顺序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:53:21