【问题标题】:Issue with the Sort method when sorting strings with numbers [duplicate]使用数字对字符串进行排序时,Sort方法出现问题[重复]
【发布时间】:2016-12-03 09:54:51
【问题描述】:

我正在尝试按字母顺序对充满字符串的ArrayList 进行排序。当我调用 Sort 方法时,字母表似乎可以很好地排序,但是当涉及数字时,Sort 方法似乎排序不正确。

以这段代码为例:

ArrayList list = new ArrayList ();

list.Add ("img149");
list.Add ("img15");
list.Add ("a");

list.Sort ();

for (int i = 0; i < list.Count (); i++) {
    Console.WriteLine (list [i]);
}

这似乎打印出来:

a
img_149
img_15

字符串“a”排序正常,但其他两个字符串排序不正确。我想我明白为什么这是因为“4”出现在“5”之前,但是 149 确实高于 15,在这种情况下,应该首先打印 15 的字符串。

对于我的情况,我永远不知道字符串是什么(字符串代表我的程序中的文件名),并且名称按字母顺序按数字顺序排序(1、2、150、300、等等。)。有没有人对如何纠正这个问题有任何想法?

【问题讨论】:

  • 谷歌自然排序。字符串包含数字而不是数字,因此它们排序正确。
  • 我使用的解决方案可以在here找到。
  • @Plutonix 感谢您提及自然排序。这就是我最终用来发现问题的方法,以及关于该主题的更多讨论。这就解释了为什么我之前没有找到任何关于它的信息——没有使用正确的术语。

标签: c# sorting methods


【解决方案1】:

排序正确。试试这个:

List<string> sortedFileNames = list.Cast<string>().OrderBy(s =>
{
    string numericStr = Regex.Match(s, @"\d+").Value;
    if (numericStr == "")
    {
        return s; // file name does not include number, so just sort by actual file name.
    }
    else
    {
        return s + numeric.PadLeft(10, '0'); // file name includes numbers, so sort by file name with number zero-padded to fixed length of 10.
    }
}).ToList();

【讨论】:

  • 就像我说的,我知道这是正确的排序,但是这对我来说是错误的排序。请阅读我在第二段中明确说明的帖子。我还说我永远不知道字符串代表什么,因为它们是文件名,因此我无法更改我的命名约定。
  • @SIRmisterD 抱歉,我已经更新了答案。
  • 不用担心。 :) 现在查看您发布的代码,我认为这对我不起作用,因为如果文件确实包含数字,我永远不知道数字在哪里。因此,将其固定为 10 可能会导致一些问题。
  • @SIRmisterD 明白了。我的解决方案假定数字仅位于文件名的末尾。这里的答案应该对您有所帮助:stackoverflow.com/a/11720793/6196648 像这样称呼它:List&lt;string&gt; sortedList = list.Cast&lt;string&gt;().OrderByAlphanumeric(s =&gt; s).ToList();
  • 嗯...当我尝试在我的脚本中使用该代码时,似乎希望我的类定义为静态,这会导致一大堆其他问题。我是否必须在单独的脚本中使用该代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
相关资源
最近更新 更多