How to convert a string to List<int>

Asked

Viewed 3,072 times

12

I have the following variable and would like to convert it to an integer list:

string variavel = "1,2,3";

How to convert it to a list of integers?

3 answers

16


Yes,

string variavel = "1,2,3";
var numeros = variavel.Split(',').Select(Int32.Parse).ToList();

or

var numeros = variavel.Split(',').Select(item => int.Parse(item)).ToList();
  • Thanks @Maiconcarraro, it worked here :-)

4

It can also be done this way:

string variavel = "1,2,3";

List<int> inteiros = new List<int>();

foreach (var valor in variavel.Split(','))
   inteiros.Add(int.Parse(valor));

Another, simpler way would be this way.

 List<int> num = Array.ConvertAll(variavel.Split(','), s => int.Parse(s)).ToList(); 
  • Thanks @Meuchapeu, it worked out here too this way, but I’m using a tool Resharper and it talks to replace the List<int> for var. Is there a problem?

  • 2

    @Danilo It’s more the same programming style, the reason Resharper does this is because he always tries to facilitate refactoring so when you have a method that can change the return type if you have using var will not change anything, now if you specified the type will need to refactor later.

3

If I could use the array just use the Split(). And if you had a method that would return list instead of array, would also simplify, but I don’t even think there should be:

var lista = "1, 2, 3".Split(',').Select(int.Parse).ToList();

Source.

using System;
using System.Linq;
                    
public class Program {
    public static void Main() {
        var lista = "1, 2, 3".Split(',').Select(int.Parse).ToList();
        Console.WriteLine(lista.GetType());
        foreach (var item in lista) {
            Console.WriteLine(item);
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • 1

    More where I’m converting to a list of the whole type?

  • 1

    @Danilo it’s true, I didn’t read the int then there is no way really, I will change, will be equal the answer accepted, but I will give the credit of where it has this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.