Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Version Identifiers

Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version.

Suggestions or improvements, please!

    /// <summary>     /// Compares two specified version strings and returns an integer that      /// indicates their relationship to one another in the sort order.     /// </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)     {         char[] splitTokens = new char[] {'.', ','};         string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);         string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);         int[] versionA = new int[4];         int[] versionB = new int[4];          for (int i = 0; i < 4; i++)         {             versionA[i] = Convert.ToInt32(strAsplit[i]);             versionB[i] = Convert.ToInt32(strBsplit[i]);         }          // now that we have parsed the input strings, compare them         return RecursiveCompareArrays(versionA, versionB, 0);     }      /// <summary>     /// Recursive function for comparing arrays, 0-index is highest priority     /// </summary>     private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx)     {         if (versionA[idx] < versionB[idx])             return -1;         else if (versionA[idx] > versionB[idx])             return 1;         else         {             Debug.Assert(versionA[idx] == versionB[idx]);             if (idx == versionA.Length - 1)                 return 0;             else                 return RecursiveCompareArrays(versionA, versionB, idx + 1);         }     } 

@ Darren Kopp:

The version class does not handle versions of the format 1.0.0.5.

like image 556
Nick Avatar asked Aug 27 '08 15:08

Nick


People also ask

How to compare versions in java?

compareTo(version1_2) > 0); Here, we can confirm that the 1.1 version is less than the 1.2 version, and the 1.3 version is greater than the 1.2 version.


1 Answers

Use the Version class.

Version a = new Version("1.0.0.0"); Version b = new Version("2.0.0.0");  Console.WriteLine(string.Format("Newer: {0}", (a > b) ? "a" : "b")); // prints b 
like image 195
Darren Kopp Avatar answered Sep 20 '22 04:09

Darren Kopp