Sorting strings containing numbers in a user friendly way

前端 未结 3 472
滥情空心
滥情空心 2020-12-10 01:34

Being used to the standard way of sorting strings, I was surprised when I noticed that Windows sorts files by their names in a kind of advanced way. Let me give you an examp

相关标签:
3条回答
  • 2020-12-10 02:10

    The absolute easiest way, I found, was isolate the string you want, so in the OP's case, Path.GetFileNameWithoutExtension(), remove the non-digits, convert to int, and sort. Using LINQ and some extension methods, it's a one-liner. In my case, I was going on directories:

    Directory.GetDirectories(@"a:\b\c").OrderBy(x => x.RemoveNonDigits().ToIntOrZero())
    

    Where RemoveNonDigits and ToIntOrZero are extensions methods:

    public static string RemoveNonDigits(this string value) {
        return Regex.Replace(value, "[^0-9]", string.Empty);
    }
    
    public static int ToIntOrZero(this string toConvert) {
        try {
            if (toConvert == null || toConvert.Trim() == string.Empty) return 0;            
            return int.Parse(toConvert);
        } catch (Exception) {
            return 0;
        }
    }
    

    The extension methods are common tools I use everywhere. YMMV.

    0 讨论(0)
  • 2020-12-10 02:13

    Jeff wrote up an article about this on Coding Horror. This is called natural sorting, where you effectively treat a group of digits as a single "character". There are implementations out there in every language under the sun, but strangely it's not usually built-in to most languages' standard libraries.

    0 讨论(0)
  • 2020-12-10 02:28

    The mother of all sorts:

    ls '*.mp3' | sort --version-sort

    0 讨论(0)
提交回复
热议问题