如何打破此字符串并对版本号进行排序

时间:2010-05-13 23:36:32

标签: .net asp.net vb.net sorting

我有一个ASP应用程序,它有一个字符串数组(除此之外):

    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

如何按版本降序对这些字符串进行排序?

2 个答案:

答案 0 :(得分:2)

创建一个键选择器,将版本转换为数字:

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);

输出:

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

答案 1 :(得分:1)

这是@ Guffa代码的VB版本。我还使用内置的.Net Version类型缩短了它,该类型已经可以排序:

    '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