c# - linq - 字符串列表 - 仅按字母排序,然后按数字排序

标签 c# linq

例如:

这个数组:

a 2
a 10
a

应该在排序之后:

a
a 2
a 10

我尝试了这个,但它不起作用:顺序错误。

 ... 
.OrderBy(s => s.name)
.ThenBy(s => {
   var stringNumber = Regex.Match(s.name, @"\d+").Value;

   return string.IsNullOrEmpty(stringNumber) 
     ? 0 
     : int.Parse(stringNumber);
 });

最佳答案

我建议显式提取条件:正则表达式中的 namenumber 组:

  var list = new List<string>() {
    "a",
    "a 4",
    "b 1",
    "a 2",
    "a 11"
  };

  var result = list
    .Select(item => new {
         value = item,
         match = Regex.Match(item, @"^(?<name>.*?)\s*(?<number>[0-9]*)$"), 
       })
    .OrderBy(item => item.match.Groups["name"].Value)
    .ThenBy(item => item.match.Groups["number"].Value.Length)
    .ThenBy(item => item.match.Groups["number"].Value)
    .Select(item => item.value);

测试:

Console.WriteLine(string.Join(Environment.NewLine, result));

结果:

a
a 2
a 4
a 11
b 1

关于c# - linq - 字符串列表 - 仅按字母排序,然后按数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47919760/

相关文章:

c# - 意外的 Linq OrderBy

c# - "LINQ to Entities does not recognize the method ' Int32 Parse(System.String)' 的解决方法

c# - 我们如何解决将 Access DB 从生产服务器转移到实时服务器的日期时间问题

c# - 无法添加对 System.Web.Hosting 的引用

c# - 将字符串数据绑定(bind)到文本框

c# - TransformedBitmap 缩放模式

使用 AND 和 OR 的 C# 谓词生成器

c# - 编辑 LINQ to SQL 对象模型

linq - Linq是这个字符串。比较查询效率低下,有没有更好的方法?

c# - 与时间无关的日期列表