How to convert a string to Listint

12

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

string variavel = "1,2,3";

Is there a way to convert it to a list of integers?

    
asked by anonymous 06.08.2015 / 14:16

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();
    
06.08.2015 / 14:23
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(); 
    
06.08.2015 / 14:26
3

If you could use array just use Split ". And if I had a method that returns list instead of array , it would also simplify, but neither do I think it should exist:

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

Font .

See running on dotNetFiddle :

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);
        }
    }
}
    
06.08.2015 / 14:40