1

我想做多部分字母数字字符串的比较。

我收到一个字符串,其中包含系统中当前运行的 sw 版本。

只有当系统运行在某个 sw 版本或更高版本上时,我才想做一些操作。

例如,如果系统运行的是 sw 版本 3.D 或更高版本(3.E,..),我会执行一些操作。如果系统运行的是较低的 sw 版本(3.B,..),我不这样做。

4

1 回答 1

6

创建一个IComparer<string>,例如:

class VersionComparer : IComparer<string>
{
    public int Compare(string a, string b)
    {
        // omitted error checking for brevity
        var sa = a.Split('.');
        var majorA = sa[0];
        var minorA = sa[1];

        var sb = b.Split('.');
        var majorB = sb[0];
        var minorB = sb[1];

        if(majorA == majorB)
            return minorA.CompareTo(minorB);

        return majorA.CompareTo(majorB); // assuming a single letter of always the same case
    }
}

并像这样使用它:

var comparer = new VersionComparer();
Debug.Assert(comparer.Compare("2.C", "2.D") < 0);  // 2.C is older
Debug.Assert(comparer.Compare("2.D", "2.D") == 0); // same
Debug.Assert(comparer.Compare("2.E", "2.D") > 0);  // 2.E is newer
Debug.Assert(comparer.Compare("3.C", "2.D") > 0);  // 3.C is newer
Debug.Assert(comparer.Compare("0.A", "0.B") < 0);  // 0.A is older

请注意,最好以合适的类型存储您的版本号,例如:

class Version
{
    public int Major {get; private set;}
    public string Minor {get; private set;}

    public Version(string s)
    {
        // omitted error checking for brevity
        // assuming a single letter of always the same case
        var sa = s.Split('.');
        Major = int.Parse(sa[0]);
        Minor = sa[1];
    }

    public static bool operator <(Version one, Version another)
    {
        if (one.Major == another.Major)
            return one.Minor.CompareTo(another.Minor) < 0;
        return one.Major< another.Major;
    }

    public static bool operator >(Version one, Version another)
    {
        return !(one < another);
    }

    public static bool operator ==(Version one, Version another)
    {
        return one.Major == another.Major && one.Minor == another.Minor;
    }

    public static bool operator !=(Version one, Version another)
    {
        return !(one == another);
    }

    public static bool operator >=(Version one, Version another)
    {
        return (one > another || one == another);
    }

    public static bool operator <=(Version one, Version another)
    {
        return (one < another || one == another);
    }
}

并快速检查:

Debug.Assert(new Version("2.C")  < new Version("2.D"));
Debug.Assert(new Version("2.D")  > new Version("2.C"));
Debug.Assert(new Version("4.C")  > new Version("2.D"));
Debug.Assert(new Version("4.C")  == new Version("4.C"));
Debug.Assert(new Version("4.C")  >= new Version("2.D"));
于 2013-09-06T14:12:18.487 回答