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

前端 未结 3 421
鱼传尺愫
鱼传尺愫 2020-12-06 05:35

I have a List like this:

var l = new List {\"bla 1.txt\",\"bla 2.txt\",\"bla 10.txt\",\"bla 3.txt\"};

If i call l.Sort(), the

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 05:50

    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.

提交回复
热议问题