How to convert a string into Int collection

Below is my string.

var str = "1,2,3,4,5";

var strArr = str.split(","); // this gives me an array of type string

List<int> intCol = new List<int>(); //I want integer collection. Like

What I am doing is:-

foreach(var v in strArr)
{
     intCol.add(Convert.ToInt(v));
}

Is it right way to do it?

Jon Skeet
people
quotationmark

Well that's a way of doing it, certainly - but LINQ makes it a lot easier, as this is precisely the kind of thing it's designed for. You want a pipeline that:

  • Splits the original string into substrings
  • Converts each string into an integer
  • Converts the resulting sequence into a list

That's simple:

List<int> integers = bigString.Split(',').Select(int.Parse).ToList();

The use of int.Parse as a method group is clean here, but if you're more comfortable with using lambda expressions, you can use

List<int> integers = bigString.Split(',').Select(s => int.Parse(s)).ToList();

people

See more on this question at Stackoverflow