C#使用通配符比较两个版本
本文关键字:两个 版本 通配符 比较 | 更新日期: 2023-09-27 17:58:33
让我们假设我有两个"版本"的东西。一个是实际版本(如1.5.2.1)
另一个是这样的字符串:1.*或1.5.*.
我想验证通配符对于实际版本是否为true。
为了更好地理解:
Validation(1.5.2.1,1.*) should be true.
Validation(1.5.2.1,1.5.*) should also be true.
Validation(1.5.2.1,1.5.1.*) should be false.
Validation(2.5.0.0,1.*) should be false.
Validation(1.5,2.*) should also return true. // This Case breaks all of my attempts.
Validation for "*" only should always be true.
有人能帮我吗?
您可以使用Split
和Zip
组合两个拆分的结果并遍历项目:
string value = "1.5.2.1";
string pattern = "1.5.*";
var parts = value.Split('.').Zip(pattern.Split('.'), (valuePart, patternPart) => new { Value = valuePart, Pattern = patternPart });
bool result = true;
foreach (var part in parts)
{
if (part.Pattern == "*")
{
result = true;
break;
}
int p = Int32.Parse(part.Pattern);
int v = Int32.Parse(part.Value);
if (p < v)
{
result = false;
break;
}
else if (p > v)
{
result = true;
break;
}
}
针对更新问题的更新答案:
public static bool Validation(Version installedVersion, string allowedVersions)
{
var components = new [] {int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue};
var split = allowedVersions.Split('.');
for (int i = 0; i < split.Length; ++i)
if (split[i] != "*")
components[i] = int.Parse(split[i]);
return installedVersion <= new Version(components[0], components[1], components[2], components[3]);
}
样品测试代码:
Console.WriteLine(Validation(new Version("1.5.2.1"), "1.*")); // True
Console.WriteLine(Validation(new Version("1.5.2.1"), "1.5.*")); // True
Console.WriteLine(Validation(new Version("1.5.2.1"), "1.5.1.*")); // False
Console.WriteLine(Validation(new Version("2.5.0.0"), "1.*")); // False
Console.WriteLine(Validation(new Version("1.1.0.0"), "2.*")); // True
Console.WriteLine(Validation(new Version("2.5.0.0"), "*")); // True
[EDIT:稍微简化了代码]