简体   繁体   中英

sorting on List<string> with middle 2 character

I like to sort a list with middle 2 character. for example: The list contains following:

body1text
body2text
body11text
body3text
body12text
body13text

if I apply list.OrderBy(r => r.body), it will sort as follows:

body1text
body11text
body12text
body13text
body2text
body3text

But I need the following result:

body1text
body2text
body3text
body11text
body12text
body13text

is there any easy way to sort with middle 2 digit character?

Regards Shuvra

The issue here is that your numbers are compared as strings, so string.Compare("11", "2") will return -1 meaning that "11" is less than "2". Assuming that your string is always in format "body" + n numbers + "text" you can match numbers with regex and parse an integer from result:

new[] 
{
    "body1text"
    ,"body2text"
    ,"body3text"
    ,"body11text"
    ,"body12text"
    ,"body13text"
}
.OrderBy(s => int.Parse(Regex.Match(s,@"\d+").Value))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM