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

如何使用LINQ对包含数字的字符串列表进行排序?

使用LINQ对分隔字符串列表排序的实现方法

给定输入列表:

{"rajesh|51|32|asd", "nitin|71|27|asd", "test|11|30|asd"}

需要排序得到:

{"test|11|30|asd", "rajesh|51|32|asd", "nitin|71|27|asd"}

观察可知,排序规则是按每个字符串分割后的第二个数字字段(|分隔的第2个元素)升序排列,用LINQ可以这样实现:

基础实现代码

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<string> inputList = new List<string> 
        { 
            "rajesh|51|32|asd", 
            "nitin|71|27|asd", 
            "test|11|30|asd" 
        };

        // 按分割后的第二个数字字段升序排序
        List<string> sortedList = inputList
            .OrderBy(item => int.Parse(item.Split('|')[1]))
            .ToList();

        // 输出验证
        foreach (var item in sortedList)
        {
            Console.WriteLine(item);
        }
    }
}

代码说明

  • item.Split('|'):将每个字符串按|分割为字符串数组,例如"rajesh|51|32|asd"会被拆分为["rajesh", "51", "32", "asd"]
  • [1]:取分割后的第二个元素(数组索引从0开始),即代表排序依据的数字字符串
  • int.Parse(...):将数字字符串转为整数,确保按数值大小排序(而非字符串字典序,避免出现"100"排在"20"前面的问题)
  • OrderBy:LINQ提供的升序排序方法,基于提取的整数值对原列表排序
  • ToList():将排序后的IEnumerable<string>转换为List<string>类型

健壮性优化(可选)

如果列表中可能存在格式不合法的字符串(比如分割后没有第二个元素、无法转为整数),可以用int.TryParse避免抛出异常,同时指定格式错误项的排序位置:

List<string> sortedList = inputList
    .OrderBy(item => 
    {
        // 尝试解析第二个字段为整数
        if (int.TryParse(item.Split('|')?[1], out int sortNum))
            return sortNum;
        // 格式错误的项默认排到最后
        return int.MaxValue;
    })
    .ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:52:39