I need to convert a string of comma separated integers into a list of integers.
What is the best way to do this?
I can do it below but am worried about the performance – Is there a better more efficient way to do this?
public IEnumerable<int> GetListOfIds()
{
string Ids = "1,4,5,7,12"; // would be passed into method
List<int> _result = Ids.Split(',')
.ToList()
.Select(item => int.Parse(item))
.ToList();
return _result;
}
There’s no need to call
ToList, but otherwise your code looks fine:You may also want to consider adding error handling in case the input string is invalid: