San*_*r M 117 c# versioning string compare version
如何比较版本号?
例如:
x = 1.23.56.1487.5
y = 1.24.55.487.2
Joh*_*hnD 273
你可以使用Version类吗?
http://msdn.microsoft.com/en-us/library/system.version.aspx
它有一个IComparable接口.请注意,这不适用于您所显示的5部分版本字符串(这真的是您的版本字符串吗?).假设您的输入是字符串,这是一个使用普通.NET 4部分版本字符串的工作示例:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
除了@JohnD的回答之外,可能还需要比较部分版本号而不使用Split('.')或其他字符串< - > int转换膨胀.我刚刚编写了一个扩展方法CompareTo和一个额外的参数 - 要比较的版本号的重要部分的数量(在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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56230 次 |
最近记录: |