Reputation: 997
I have two strings
string A = "1.0.0.0";
string B = "1.0.0.1";
I need to evaluate somehow that B is greater than A (version wise) either converting those two strings to integers or decimals or something.
I tried the following
Decimal S = Convert.ToDecimal(A);
int S = Convert.ToInt32(A);
but keep getting the following error, "Input string was not in a correct format."
Any help will be appreciated.
Upvotes: 4
Views: 13590
Reputation: 286
You can take a look at System.Version
class.
If the strings are in this format or can be converted to a version.
Version have comparers
Upvotes: 3
Reputation: 11
Instead of using VersionClass a fast approach would be something like this.
string A = "1.0.0.0";
string B = "1.0.0.1";
int versionA = Convert.ToInt32(A.Replace(".", string.Empty));
int versionB = Convert.ToInt32(B.Replace(".", string.Empty));
if (b>a)
//something will happen here
Replace changes the first string to the second one in this case string.Empty equals to "".
Upvotes: -2
Reputation: 13877
See the Version Class.
You're able to do something like this:
Version a = new Version("1.0.0.0");
Version b = new Version("1.0.0.1");
if (b>a) //evaluates to true
blah blah blah
I haven't personally tested this exact scenario, but the Version
class allows you to use comparison operators like I've shown here.
Upvotes: 20
Reputation: 498972
If your string has at most 4 numeric parts (separated by .
), you can use the Version
class to get a strongly typed entity that corresponds to these strings. Version
implements the different comparison operators (==
, >
, <
etc...) in the expected manner, so you can find out which is greater:
var a = new Version(A);
var b = new Version(B);
if(a > b)
// a is larger
else if (a < b)
// b is larger
else
// they are identical
If there are more than 4 parts, you will need to split each string to its numeric components, convert each one to a numeric equivalent and compare the two resulting collections.
Something like:
var aParts = A.Split('.');
var bParts = B.Split('.');
// assumes the string have the same number of parts
for(int i = 0; i < aParts.Length; i++)
{
var currA = int.Parse(aParts[i]);
var currB = int.Parse(bParts[i]);
if(currA == currB)
continue;
if(currA > currB)
// A is greater than B
else
// B is greater than A
}
Upvotes: 3
Reputation: 4600
Split on the ".". Then convert each part to an int. Starting from the left: if A's fragment is lower, then report that A is first. If B's fragment is lower, then report that B is first. Otherwise, move to the next fragment. If you're at the last fragment already, report that they are equal.
If your strings have at most four parts (like version numbers), then as others suggested it's easier to use the System.Version class.
Upvotes: 1