Converting a string to int?

9

What is the best way to convert a string variable to another variable of type int? , that is, nullable of int ? Performance is very important in this case because I will be converting multiple values into a loop.

Would it be possible to do this conversion in a line of code? I ask this because there will be many consecutive lines of code doing this operation and would be a "plus" if I did not increase my code a lot with data conversion.

    
asked by anonymous 24.02.2014 / 07:53

6 answers

4

You can use the following function to do the conversion effectively without many lines:

public static int? StringToNullableInt(string strNum)
{
    int outInt;
    return int.TryParse(strNum, out outInt) ? outInt : (int?)null;
}

Or to do inline conversions using LINQ, you could do this:

var strNumeros = new[] { "1267", "-835", "9", "", "xpto" };
int outInt;
var valores = strNumeros
    .Select(strNumero => int.TryParse(strNumero, out outInt) ? outInt : (int?)null)
    .ToList();

This way you convert all strings to IEnumerable<string> in almost a few lines.

    
24.02.2014 / 14:19
6

You can also implement the @MiguelAngelo response in class extension form:

namespace SeuProjeto.Extensions 
{
    public static class StringExtension 
    {
        public static Nullable<int> ToInt(this String value) 
        {
            int outInt;
            return int.TryParse(value, out outInt) ? outInt : (int?)null;
        }
    }
}

The same example in LINQ would look like this:

var strNumeros = new[] { "1267", "-835", "9", "", "xpto" };
int outInt;
var valores = strNumeros
    .Select(strNumero => strNumero.ToInt())
    .ToList();
    
24.02.2014 / 20:39
4

There may be several ways to do this. I use TryParse to convert string to int .

Example:

var varStringConvert = "123";
int varInt;
if ((int.TryParse(varStringConvert.ToString(), out varInt))) { 

}

The code above shows the variable varStringConvert with the value 123 which is integer but the compiler does not guess and thinks it is a variable of type string . So we have to try to convert to integer. So I make a TryParse of string for variable int varInt .

    
24.02.2014 / 10:24
2

The Convert class can be used. to convert a% set_def% previously defined, such as:

string name="12345";

Convert.ToInt32 (name);

    
24.02.2014 / 12:43
1

Converts and verifies whether or not to convert:

string str = '0123'; // ou qualquer coisa
int i = 0; // inicializa variável que receberá o valor inteiro

// Tenta converter str para inteiro (com saída na variável i)
if (Int32.TryParse(str, out i)) {
    Console.WriteLine(i); // Se conseguiu imprime variável
} else {
    Console.WriteLine ("Erro ao converter '" + str + "' para inteiro."); // Mensagme de erro
}

or

string str = '0123'; // ou qualquer coisa
int i = 0; // inicializa variável que receberá o valor inteiro    
try
{
    i = Convert.ToInt32(str);
    Console.WriteLine(i); // Se conseguiu imprime variável
}
catch (FormatException e)
{
    Console.WriteLine("String inválida para conversão."); // Erro
}
catch (OverflowException e)
{
    Console.WriteLine ("Overflow. Valor inteiro ultrapassou o limtie."); // Erro
}

Create a specific class to solve this and call a method you will trust, ie you will invoke a method to resolve this conversion and will make sure that even if the string is invalid it will return an integer value to You.

Example, if you only need positive integer values, whenever the function returns you -1 it would signal that it gave error. Etc.

The maintenance of the code would be done in one place, within that method in the particular class that solves this conversion problem.

Performance is not directly influenced in either case. If you are sure that the value is integer, not checking would gain little performance, which in my opinion is not worth, since a crash in the application would be worse if your function received a string that did not contain a possible integer value.

    
24.02.2014 / 13:25
0

There are at least three types of conversions (Parse, TryParse and Convert), ideally you would understand how they work and use them according to your needs.

You can understand more about them in the post that I write below written by Vitor Mendes (MVP) that explains this subject:

Parse, Convert, or TryParse

    
28.02.2014 / 14:32