Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert comma separated string into a List<int> [duplicate]

Tags:

string

c#

.net

list

People also ask

How do you convert comma separated numbers to lists in Python?

Input a comma - separated string using raw_input() method. Split the elements delimited by comma (,) and assign it to the list, to split string, use string. split() method. The converted list will contains string elements.


Here is one way of doing it:

List<int> TagIds = tags.Split(',').Select(int.Parse).ToList();

If you want to include some simple validation and skip over invalid values (instead of throwing an exception), here's something that uses TryParse:

string csv = "1,2,3,4,a,5";
int mos = 0;
var intList = csv.Split(',')
                    .Select(m => { int.TryParse(m, out mos); return mos; })
                    .Where(m => m != 0)
                    .ToList();

//returns a list with integers: 1, 2, 3, 4, 5

EDIT: Here is an updated query based on feedback by Antoine. It calls TryParse first to filter out any bad values, and then Parse to do the actual conversion.

string csv = "1,2,3,4,a,5,0,3,r,5";
int mos = 0;
var intList = csv.Split(',')
                    .Where(m => int.TryParse(m, out mos))
                    .Select(m => int.Parse(m))
                    .ToList();

//returns a list with integers: 1, 2, 3, 4, 5, 0, 3, 5

Edit 2: An updated query for C# 7.0, thanks to feedback from Charles Burns. Note that we get rid of the extra mos variable with this approach, so it's a bit cleaner.

string csv = "1,2,3,4,a,5,0,3,r,5";
var intList = csv.Split(',')
                 .Where(m => int.TryParse(m, out _))
                 .Select(m => int.Parse(m))
                 .ToList();

You can use LINQ w/ int.Parse() to convert the string[] to an IEnumerable<int> and then pass that result to the List<T> constructor:

var tagIds = new List<int>(tags.Split(',').Select(s => int.Parse(s)));

A little LINQ goes a long way:

 List<int> TagIds = tags.Split(',')
         .Select(t => int.Parse(t))
         .ToList();

Without LINQ Query , you can choose this method ,

string tags = "9,3,12,43,2";
List<string> numbers = nos.Split(',').ToList<string>();

and then you can convert this List into integer type...