将3.C与3.B和3.D进行比较

时间:2013-09-06 14:08:01

标签: c# string string-comparison

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

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

我只想在系统运行某个sw版本或更高版本时才进行某些操作。

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

1 个答案:

答案 0 :(得分: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"));