Sorting strings containing numbers in a user friendly way

前端 未结 3 478
滥情空心
滥情空心 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.

提交回复
热议问题