簡體   English   中英

按列表排序<string>中間 2 個字符</string>

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

我喜歡用中間 2 個字符對列表進行排序。 例如:該列表包含以下內容:

body1text
body2text
body11text
body3text
body12text
body13text

如果我應用 list.OrderBy(r => r.body),它將按如下方式排序:

body1text
body11text
body12text
body13text
body2text
body3text

但我需要以下結果:

body1text
body2text
body3text
body11text
body12text
body13text

有沒有簡單的方法可以用中間 2 位字符進行排序?

問候舒夫拉

這里的問題是您的數字作為字符串進行比較,因此string.Compare("11", "2")將返回-1意味着“11”小於“2”。 假設您的字符串始終采用 "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