string sNumbers = "1,2,3,4,5";
If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:
(str ?? "").Split(',').Select<string, int>(int.Parse);
If you don't want to have the current error handling behaviour, it's really easy:
text.Split(',').Select(x => int.Parse(x));
return a list instead of int array:
var numbers = sNumbers.Split(',').Select(Int32.Parse).ToList();
List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
// Uses Linq
var numbers = Array.ConvertAll(sNumbers.Split(','), int.Parse).ToList();
Reference:
http://stackoverflow.com/questions/1763613/convert-comma-separated-string-of-ints-to-int-array
http://stackoverflow.com/questions/911717/split-string-convert-tolistint-in-one-line
No comments:
Post a Comment