不使用拆分function比较版本号

我如何比较版本号?

例如:

x = 1.23.56.1487.5

y = 1.24.55.487.2

你可以使用Version类吗?

http://msdn.microsoft.com/en-us/library/system.version.aspx

它有一个IComparable接口。 要知道,这不会像你所显示的5部分版本的string(是真的是你的版本string?)。 假设你的input是string,下面是一个正常的.NET 4部分版本string的工作示例:

 static class Program { static void Main() { string v1 = "1.23.56.1487"; string v2 = "1.24.55.487"; var version1 = new Version(v1); var version2 = new Version(v2); var result = version1.CompareTo(version2); if (result > 0) Console.WriteLine("version1 is greater"); else if (result < 0) Console.WriteLine("version2 is greater"); else Console.WriteLine("versions are equal"); return; } } 

如果您可以使用major.minor.build.revisionscheme,您可以使用.Net 版本类。 否则,你将不得不从左到右执行一些parsing,直到你有两个版本相同的区别或者返回。

 public int compareVersion(string Version1,string Version2) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"([\d]+)"); System.Text.RegularExpressions.MatchCollection m1 = regex.Matches(Version1); System.Text.RegularExpressions.MatchCollection m2 = regex.Matches(Version2); int min = Math.Min(m1.Count,m2.Count); for(int i=0; i<min;i++) { if(Convert.ToInt32(m1[i].Value)>Convert.ToInt32(m2[i].Value)) { return 1; } if(Convert.ToInt32(m1[i].Value)<Convert.ToInt32(m2[i].Value)) { return -1; } } return 0; } 

除了@JohnD的答案,可能需要比较只有部分版本号,而不使用拆分('。')或其他string< – > int转换膨胀。 我刚刚写了一个扩展方法CompareTo与1个附加参数 – 要比较的版本号(1和4之间)的重要部分的数量。

 public static class VersionExtensions { public static int CompareTo(this Version version, Version otherVersion, int significantParts) { if(version == null) { throw new ArgumentNullException("version"); } if(otherVersion == null) { return 1; } if(version.Major != otherVersion.Major && significantParts >= 1) if(version.Major > otherVersion.Major) return 1; else return -1; if(version.Minor != otherVersion.Minor && significantParts >= 2) if(version.Minor > otherVersion.Minor) return 1; else return -1; if(version.Build != otherVersion.Build && significantParts >= 3) if(version.Build > otherVersion.Build) return 1; else return -1; if(version.Revision != otherVersion.Revision && significantParts >= 4) if(version.Revision > otherVersion.Revision) return 1; else return -1; return 0; } }