How to sort number in alphanumeric

前端 未结 5 429
失恋的感觉
失恋的感觉 2021-01-03 01:16

Input:

SHC 111U,SHB 22x,, SHA 5555G

Needed output:

SHB 22X, SHC 111U, SHA 5555G

I

5条回答
  •  佛祖请我去吃肉
    2021-01-03 01:41

    If it is possible to have a plate without a number then you should check for that.

    static int SortPlate(string plate)
    {
        int plateNumber;
        Regex regex = new Regex(@"\d+");
        Int32.TryParse(regex.Match(plate).Value, out plateNumber);
    
        return plateNumber;
    }
    
    static void Main(string[] args)
    {
        IEnumerable data = new List() {"SHC 111U", "SHB 22x", "SHA 5555G", "HOT STUFF"};
    
        var sortedList = from z in data
                         orderby SortPlate(z)
                         select z;
    
        foreach (string plate in sortedList)
        {
            Console.WriteLine(plate);
        }
    
    }
    

    If it is absolutely impossible and the end of the world would come before there could ever be a plate without numbers then this shortened form will work:

    static void Main(string[] args)
    {
        IEnumerable data = new List() {"SHC 111U", "SHB 22x", "SHA 5555G"};
    
        Regex regex = new Regex(@"\d+");
        var sortedList = from z in data
                         orderby Int32.Parse(regex.Match(z).Value)
                         select z;
    
        foreach (string plate in sortedList)
        {
            Console.WriteLine(plate);
        }
    
    }
    

提交回复
热议问题