-
-
Save kirillrybin/6b2f058bd65fc2dafa9c to your computer and use it in GitHub Desktop.
C# CompareVersions via http://stackoverflow.com/questions/30494/compare-version-identifiers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Compare versions of form "1,2,3,4" or "1.2.3.4". Throws FormatException | |
/// in case of invalid version. | |
/// </summary> | |
/// <param name="strA">the first version</param> | |
/// <param name="strB">the second version</param> | |
/// <returns>less than zero if strA is less than strB, equal to zero if | |
/// strA equals strB, and greater than zero if strA is greater than strB</returns> | |
public static int CompareVersions(string strA, string strB) | |
{ | |
var vA = new System.Version(strA.Replace(",", ".")); | |
var vB = new System.Version(strB.Replace(",", ".")); | |
return vA.CompareTo(vB); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void Main(string[] args) | |
{ | |
Test("1.0.0.0", "1.0.0.1", -1); | |
Test("1.0.0.1", "1.0.0.0", 1); | |
Test("1.0.0.0", "1.0.0.0", 0); | |
Test("1, 0.0.0", "1.0.0.0", 0); | |
Test("9, 5, 1, 44", "3.4.5.6", 1); | |
Test("1, 5, 1, 44", "3.4.5.6", -1); | |
Test("6,5,4,3", "6.5.4.3", 0); | |
try | |
{ | |
CompareVersions("2, 3, 4 - 4", "1,2,3,4"); | |
Console.WriteLine("Exception should have been thrown"); | |
} | |
catch (FormatException e) | |
{ | |
Console.WriteLine("Got exception as expected."); | |
} | |
Console.ReadLine(); | |
} | |
private static void Test(string lhs, string rhs, int expected) | |
{ | |
int result = CompareVersions(lhs, rhs); | |
Console.WriteLine("Test(\"" + lhs + "\", \"" + rhs + "\", " + expected + | |
(result.Equals(expected) ? " succeeded." : " failed.")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment