Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list by Alphanumeric with decimal

I have a List<string> that I need to sort by alphanumeric but it also has a decimal. The sample looks like this:

E11.9
E13.9
E10.9
E11.65
E10.65
E11.69
E13.10
E10.10

The output I need should look like this:
E10.10
E10.65
E10.9
E11.69
E11.9
etc..

I've tried this code:

result.Sort((s1, s2) =>
{
    string pattern = "([A-Za-z])([0-9]+)";
    string h1 = Regex.Match(s1, pattern).Groups[1].Value;
    string h2 = Regex.Match(s2, pattern).Groups[1].Value;
    if (h1 != h2)
        return h1.CompareTo(h2);
    string t1 = Regex.Match(s1, pattern).Groups[2].Value;
    string t2 = Regex.Match(s2, pattern).Groups[2].Value;
    return int.Parse(t1).CompareTo(int.Parse(t2));
});

But it only seems to sort by the Letter first, then by the digits prior to the decimal place. So this is what I get:
E10.9
E10.65
E10.10
E11.9
E11.69
etc..

Am I missing something in the regex? Or is there a better way to accomplish this?

like image 793
Kieran Quinn Avatar asked Dec 09 '25 06:12

Kieran Quinn


2 Answers

Can you just do this?:

Test data:

var ls=new List<string>
    {
    "E11.9",
    "E13.9",
    "E10.9",
    "E11.65",
    "E10.65",
    "E11.69",
    "E13.10",
    "E10.10",
    };

Linq:

var result= ls
             .OrderBy (l =>l.Substring(0,1))
             .ThenBy(l =>double.Parse(l.Substring(1), CultureInfo.InvariantCulture))
             .ToList();
like image 94
Arion Avatar answered Dec 10 '25 18:12

Arion


Building on Arion's answer:

var result = list.OrderBy(l => l[0]).ThenBy(l => double.Parse(l.Substring(1));

So first you'd sort by the letter and after that by the number after the letter. In case you need to handle different culture settings in double.Parse, you'd have to supply that there. See MSDN on Double.Parse.

like image 29
germi Avatar answered Dec 10 '25 18:12

germi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!