C# 使用通配符比较两个版本

C# Compare two versions using wildcard

假设我有两个 "versions" 东西。 一个是实际版本(例如 1.5.2.1)

另一个是这样的字符串:1.* 或 1.5.*.

我想验证通配符是否适用于实际版本。

为了更好地理解:

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.

谁能帮我解决这个问题?

您可以使用 SplitZip 组合两个拆分结果并遍历项目:

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

[编辑:稍微简化了代码]