简体   繁体   English

按列表排序<string>中间 2 个字符</string>

[英]sorting on List<string> with middle 2 character

I like to sort a list with middle 2 character.我喜欢用中间 2 个字符对列表进行排序。 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:如果我应用 list.OrderBy(r => r.body),它将按如下方式排序:

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?有没有简单的方法可以用中间 2 位字符进行排序?

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".这里的问题是您的数字作为字符串进行比较,因此string.Compare("11", "2")将返回-1意味着“11”小于“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:假设您的字符串始终采用 "body" + n numbers + "text" 格式,您可以将数字与正则表达式匹配并从结果中解析 integer:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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