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?
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?
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();
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();
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);
}
}
}