Search code examples
c#.netlistsortingalphanumeric

How to sort descending a string list contains strings with alphabets & numbers in C# .net?


I have values in a string list like

AB1001_A
AB1001_B
AB1002_2
AB1002_C
AB1003_0
AB1003_
AB1003_B
AB1003_A
AB1001_0
AB1001_1
AB1001_2
AB1001_C
AB1002_B
AB1002_A

And I wanted to sort this by ascending order and the suffixes in descending order like below

AB1001_2
AB1001_1
AB1001_0
AB1001_C
AB1001_B
AB1001_A
AB1002_0
AB1002_B
AB1002_A
AB1003_0
AB1003_B
AB1003_A
AB1003_

How can I code it in C#.net?


Solution

  • Finally I got the soln by this

    var mystrings = new []
                {
                    "AB1001_A",
                    "AB1001_B",
                    "AB1002_2",
                    "AB1002_C",
                    "AB1003_0",
                    "AB1003_",
                    "AB1003_B",
                    "AB1003_A",
                    "AB1001_0",
                    "AB1001_1",
                    "AB1001_2",
                    "AB1001_C",
                    "AB1002_B",
                    "AB1002_A",
                };
    
    
    mystrings.Cast<string>().OrderBy(x => PadNumbers(x));
    

    and then PadNumbers function as like below

            public static string PadNumbers(string input)
            {
                return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
            }