Sorting a List of Strings numerically (1,2,…,9,10 instead of 1,10,2)

被刻印的时光 ゝ 提交于 2019-11-27 22:53:25

The best approach is making use of IComparer. This has already been done and can be found on code project.

Why not write something that will extract a number from a string, like this?

// Note: This could very well be a bad implementation. I'm not too great with Regex.
static int ExtractNumber(string text)
{
    Match match = Regex.Match(text, @"(\d+)");
    if (match == null)
    {
        return 0;
    }

    int value;
    if (!int.TryParse(match.Value, out value))
    {
        return 0;
    }

    return value;
}

Then you could sort your list using:

list.Sort((x, y) => ExtractNumber(x).CompareTo(ExtractNumber(y)));

This strikes me as pretty inefficient, but it should be functional at least.

You could implement your own IComparer that maybe uses a regular expression on the input ("bla 1.txt"), converts that to an int, and peforms the comparison on that parsed value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!