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?
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:
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();
See more on this question at Stackoverflow