Domanda

I'll keep this one short. I'm writing a module which will be required to compare two large integers which are input as strings (note: they are large, but not large enough to exceed Int64 bounds).

The strings are padded, so the choice is between taking the extra-step to converting them to their integer equivalent or comparing them as strings.

What I'm doing is converting each of them to Int64 and comparing them that way. However, I believe that string comparisons would also work. Seeing as I'd like it to be as efficient as possible, what are you're opinions on comparison of integers via :

string integer1 = "123";
string integer2 = "456";

if (Int64.Parse(integer1) <= Int64.Parse(integer2))

OR

string integer1 = "123";
string integer2 = "456";

if (integer1.CompareTo(integer2) < 0)
È stato utile?

Soluzione 2

Nope string comparisons will not work. You should use your first version, you have to convert this strings to numbers parsing them and then compare the numbers.

It would be good to have a look here, where explains thorougly what the CompareTo method does. In a few words:

Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.

So since "123" and "456" are strings, they compare one string to another and not the one integer to the other.

Last but not least, it would be better to use the TryParse method for parsing your numbers, since your input may be not accidentally an integer. The way you use it is fairly easy:

Int64 value = 0;
Int64.Parse(integer1, out value1);

Where the value1 is the value1 you will get after the conversion of the string integer1. So for both you values, you should use this one if statement:

if(Int64.TryParse(integer1, out value1) && Int64.TryParse(integer2, out value2)
{
    if(value1<=value2)
    {

    }
    else
    {

    }
}
else
{
    // Some error would have been happened to at least one of the two conversions.
}

Altri suggerimenti

Better to use Int64.TryParse since this is a string fields

string integer1 = "123";
string integer2 = "456";

long value1=0;
long value2=0;

long.TryParse(integer1 ,out value1); 
long.TryParse(integer2 ,out value2);

if(value1<=value2)

It's fair to question if it is worth the cost of conversion (parse). If String.CompareTo were really efficient AND the number were always of a scale and format* the the string comparison were to be reliable then you might be better off. You could measure the performance, but you'll find the convert and int comparision is faster and more robust than a string comparison.

*String compare works if number strings are of equal length with leading 0s as necessary. So '003','020', and '100' will sort correctly but'3','20', and '100' will not.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top