1
0
Files
common/AMWD.Common/Comparer/VersionStringComparer.cs

87 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace AMWD.Common.Comparer
{
/// <summary>
/// Defines a method to compare two <see cref="Version"/> strings.
/// </summary>
#if NET8_0_OR_GREATER
public partial class VersionStringComparer : IComparer<string>
{
private readonly Regex _versionRegex = VersionRegex();
#else
public class VersionStringComparer : IComparer<string>
{
private readonly Regex _versionRegex = new("([0-9.]+)", RegexOptions.Compiled);
#endif
/// <summary>
/// Compares two <see cref="Version"/> strings and returns a value indicating
/// whether one is less than, equal to, or greater than the other.
/// </summary>
/// <param name="x">The first version string.</param>
/// <param name="y">The second version string.</param>
/// <returns>
/// A signed integer that indicates the relative values of x and y, as shown in the following table:
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term>Less than zero</term>
/// <description>x is less than y.</description>
/// </item>
/// <item>
/// <term>Zero</term>
/// <description>x equals y.</description>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <description>x is greater than y.</description>
/// </item>
/// </list>
/// </returns>
public int Compare(string x, string y)
{
if (string.IsNullOrWhiteSpace(x) && string.IsNullOrWhiteSpace(y))
return 0;
if (string.IsNullOrWhiteSpace(x))
return -1;
if (string.IsNullOrWhiteSpace(y))
return 1;
string xMainVersion = _versionRegex.Match(x).Groups[1].Value;
string yMainVersion = _versionRegex.Match(y).Groups[1].Value;
string xAppendix = x.ReplaceStart(xMainVersion, "");
string yAppendix = y.ReplaceStart(yMainVersion, "");
if (xMainVersion.IndexOf('.') < 0)
xMainVersion += ".0";
if (yMainVersion.IndexOf('.') < 0)
yMainVersion += ".0";
var xVersion = Version.Parse(xMainVersion);
var yVersion = Version.Parse(yMainVersion);
int versionResult = xVersion.CompareTo(yVersion);
if (versionResult != 0)
return versionResult;
return xAppendix.CompareTo(yAppendix);
}
#if NET8_0_OR_GREATER
[GeneratedRegex("([0-9.]+)", RegexOptions.Compiled)]
private static partial Regex VersionRegex();
#endif
}
}