views:

63

answers:

2

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: 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?

+1  A: 

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
Guffa
A: 

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
Chris Haas
Im getting an error that OrderBy is not a member of System.Array
Sean P
Are you targeting the 3.5 framework or greater? If so, import System.Linq at the top of your code. If not, you'll need to rewrite because this code assumes Extension Methods which shipped with 3.5.
Chris Haas
.Net 2.0 sorry i should have said that.
Sean P
So is there an easy way to do this use 2.0?
Sean P