using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace AMWD.Common.Comparer { /// /// Defines a method to compare two strings. /// #if NET8_0_OR_GREATER public partial class VersionStringComparer : IComparer { private readonly Regex _versionRegex = VersionRegex(); #else public class VersionStringComparer : IComparer { private readonly Regex _versionRegex = new("([0-9.]+)"); #endif /// /// Compares two strings and returns a value indicating /// whether one is less than, equal to, or greater than the other. /// /// The first version string. /// The second version string. /// /// A signed integer that indicates the relative values of x and y, as shown in the following table: /// /// /// Value /// Meaning /// /// /// -1 /// x is less than y /// /// /// 0 /// x equals y /// /// /// 1 /// x is greater than y /// /// /// 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.]+)")] private static partial Regex VersionRegex(); #endif } }