C# 按前导零排序项目

C# Order Items By Leading Zeros

我需要根据包含前导 0 的字符串 属性 对 IEnumerable 中的项目进行排序。这些项目需要按 000. 然后 00. 然后转到 0.

一个简化的例子:

Unordered - ["0.4","0.1", "0.3", "00.5", "000.1", "1.2", "00.2", "2.1"]

Ordered -   ["000.1", "00.2", "00.5", "0.1", "0.3", "0.4", "1.2", "2.1"]

当前的实现是:

items.OrderBy(x => x.age);

将商品排序为 ["0.1", "0.3", "0.4", "00.2", "00.5", "000.1", "1.2", "2.1"]

由于这些是字符串,我想我可能会尝试将它们转换为小数,但我仍然没有得到我需要的顺序。

items.OrderBy(x => decimal.Parse(x.age))

[ 0.1, 000.1, 00.2, 0.3, 0.4, 00.5,  1.2, 2.1]

任何关于如何获得我需要的订单的建议将不胜感激!

我建议比较字符串;困难在于'.' < '0';要获得所需的顺序,我们可以尝试将 '.' 更改为 按字典顺序 大于任何数字的其他定界符。让它成为一个 字母 ,比如 'x':

 var result = items.OrderBy(item => item.Replace('.', 'x'));

演示:

  string[] items = new string[] {
    "0.4","0.1", "0.3", "00.5", "000.1", "1.2", "00.2", "2.1"
  };

  var result = items
    .OrderBy(item => item.Replace('.', 'x'));

  Console.Write(string.Join(", ", result));

结果:

  000.1, 00.2, 00.5, 0.1, 0.3, 0.4, 1.2, 2.1

欢迎来到 Stack Overflow, 我认为这段代码可能对您有所帮助:

items.OrderBy(x => x.age.Split('.')[0].Length).ThenBy(x => decimal.Parse(x.age));

使用此代码段,我们拆分小数点上的值,然后对第一部分的 0 计数进行排序,如果我们有两个值的前导零计数相同,我们将它们作为普通小数进行比较.

尝试以下操作:

items.OrderBy(x => x.Split(".")[0]).ThenBy(x => x.Split(".")[1]);