开发者

How to break this string and sort on version number

开发者 https://www.devze.com 2022-12-30 01:13 出处:网络
I have an ASP app that has a string array as such (there are much more than this): 7.5.0.17 Date: 05_03_10

I have an ASP app that has a string array as such (there are much more than this):

    7.5.0.17 Date: 05_03_10
    7.5.0.18 Date: 05_03_10
    7.5.0.19 Date: 05_04_10
    7.5.0.2 Date开发者_Go百科: 02_19_10
    7.5.0.20 Date: 05_06_10
    7.5.0.3 Date: 02_26_10
    7.5.0.4 Date: 03_02_10
    7.5.0.5 Date: 03_08_10
    7.5.0.6 Date: 03_12_10
    7.5.0.7 Date: 03_19_10
    7.5.0.8 Date: 03_25_10
    7.5.0.9 Date: 03_26_10
    7.5.1.0 Date: 05_06_10

How do I go about sorting these string by version descending?


Make a key selector that turns the version into a number:

string[] versions = {
  "7.5.0.17 Date: 05_03_10",
  "7.5.0.18 Date: 05_03_10",
  "7.5.0.19 Date: 05_04_10",
  "7.5.0.2 Date: 02_19_10",
  "7.5.0.20 Date: 05_06_10",
  "7.5.0.3 Date: 02_26_10",
  "7.5.0.4 Date: 03_02_10",
  "7.5.0.5 Date: 03_08_10",
  "7.5.0.6 Date: 03_12_10",
  "7.5.0.7 Date: 03_19_10",
  "7.5.0.8 Date: 03_25_10",
  "7.5.0.9 Date: 03_26_10",
  "7.5.1.0 Date: 05_06_10"
};

versions = versions.OrderBy(
  s => s.Substring(0, s.IndexOf(' ')).Split('.')
  .Aggregate(0, (n, v) => n * 100 + Int32.Parse(v))
).ToArray();

foreach (string s in versions) Console.WriteLine(s);

Output:

7.5.0.2 Date: 02_19_10
7.5.0.3 Date: 02_26_10
7.5.0.4 Date: 03_02_10
7.5.0.5 Date: 03_08_10
7.5.0.6 Date: 03_12_10
7.5.0.7 Date: 03_19_10
7.5.0.8 Date: 03_25_10
7.5.0.9 Date: 03_26_10
7.5.0.17 Date: 05_03_10
7.5.0.18 Date: 05_03_10
7.5.0.19 Date: 05_04_10
7.5.0.20 Date: 05_06_10
7.5.1.0 Date: 05_06_10


Here's the VB version of @Guffa's code. I also shortened it by using the built in .Net Version type which is already sortable:

    'Your comes from a text-file, so load your data into S
    Dim S = "7.5.0.17 Date: 05_03_10" & vbNewLine & _
    "7.5.0.18 Date: 05_03_10" & vbNewLine & _
    "7.5.0.19 Date: 05_04_10" & vbNewLine & _
    "7.5.0.2 Date: 02_19_10" & vbNewLine & _
    "7.5.0.20 Date: 05_06_10" & vbNewLine & _
    "7.5.0.3 Date: 02_26_10" & vbNewLine & _
    "7.5.0.4 Date: 03_02_10" & vbNewLine & _
    "7.5.0.5 Date: 03_08_10" & vbNewLine & _
    "7.5.0.6 Date: 03_12_10" & vbNewLine & _
    "7.5.0.7 Date: 03_19_10" & vbNewLine & _
    "7.5.0.8 Date: 03_25_10" & vbNewLine & _
    "5.7.0.9 Date: 03_26_10" & vbNewLine & _
    "7.5.1.0 Date: 05_06_10"

    Dim v2 = Split(S, vbNewLine).OrderBy(Function(f) New Version(f.Substring(0, f.IndexOf(" "c))))
    For Each v In v2
        Trace.WriteLine(v)
    Next
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号