[C#] 筆記一個小東西,關於字串數字的排序
2022-02-21
其實這是一個小事情,只是因為最近有用到不要每次寫都要查一下,乾脆自己筆記一下
簡單的說我有一堆身為字串的數字 因為增加難度 該文字為
"10,11,12,13,014,15,21,22,23,24,25,111,112,113,0114,115" 用逗點隔開但是每個都是字串
這時候,我需要將裡面的數字排序呢?
1. 直接排序 OrderBy(x=>x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sampleStr = "10,11,12,13,014,15,21,22,23,24,25,111,112,113,0114,115"; | |
var strs = sampleStr.Split(','); | |
strs = strs.OrderBy(x => x).ToArray(); | |
//一般狀況 :0114,014,10,11,111,112,113,115,12,13,15,21,22,23,24,25 | |
但是這不是我們要的吧,這時候 111 排在 11 之後就字串來看很合邏輯,但是不符合數值上的邏輯,於是網路上看到有一個做法
2. 先根據長度排序之後再排序 OrderBy(x => x.Length).ThenBy(x => x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sampleStr = "10,11,12,13,014,15,21,22,23,24,25,111,112,113,0114,115"; | |
var strs = sampleStr.Split(','); | |
strs = strs.OrderBy(x => x.Length).ThenBy(x => x).ToArray(); | |
Console.WriteLine("網路上看到做法,大部分會成功,前提是前面不能有 0 :" + string.Join(',', strs)); | |
//網路上看到做法,大部分會成功,前提是前面不能有 0 :10,11,12,13,15,21,22,23,24,25,014,111,112,113,115,0114 | |
這問題大致上沒問題,但是如果遇到前面有 0 就會因為先排長度而出現錯誤,如果你的數字字串們前面沒有0,就可以用這一招。
3. 承襲第二招,但是先把前面的 0 拿掉 .Select(x=>x.TrimStart('0')).OrderBy(x => x.Length).ThenBy(x => x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sampleStr = "10,11,12,13,014,15,21,22,23,24,25,111,112,113,0114,115"; | |
var strs = sampleStr.Split(','); | |
strs = strs.Select(x=>x.TrimStart('0')).OrderBy(x => x.Length).ThenBy(x => x).ToArray(); | |
Console.WriteLine("After FixZero :" + string.Join(',', strs)); | |
//After FixZero :10,11,12,13,14,15,21,22,23,24,25,111,112,113,114,115 | |
4. 大絕招,直接 parse 成 數字 然後再排序,這招其實最直覺最常用,但是相對也比較消耗資源
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sampleStr = "10,11,12,13,014,15,21,22,23,24,25,111,112,113,0114,115"; | |
var strs = sampleStr.Split(','); | |
strs = strs.OrderBy(x => int.Parse(x)).ThenBy(x => x).ToArray(); | |
Console.WriteLine("大絕招,直接 Parse :" + string.Join(',', strs)); | |
//大絕招,直接 Parse :10,11,12,13,14,15,21,22,23,24,25,111,112,113,114,115 | |
至於要用哪一個,就看你的需求了
reference :
標籤: .Net , ASP.net , Cloudflare
--
Yesterday I wrote down the code. I bet I could be your hero. I am a mighty little programmer.
如果這篇文章有幫助到您,簡單留個言,或是幫我按個讚,讓我有寫下去的動力...