How to split this string and sort by version number

I have an ASP application that has an array of strings as such (there are many more):

    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

      

How do I sort these lines in descending order?

+2


a source to share


2 answers


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

      

+2


a source


Here's the VB version of @Guffa's code. I also shortened it using the built-in .Net version type already sorted:



    '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

      

+1


a source







All Articles