Convert a comma separated string of numbers to an integer array using C#

1

Posted by Joe | Posted in C#, Linq | Posted on 10-06-2010

Today I needed to convert a comma separated string of numbers in an integer array. Here is how you can do it in one line using Linq:

string csv = "1,1,2,3,5,8,13,21,34";
int[] numbers = csv.Split(',').Select(n => int.Parse(n)).ToArray();

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit

Comments (1)

Thanks Joe, one suggestion on the line would be to add a trim for anyone that would add spaces between the commas:

csv..Split(‘,’).Select(n => int.Parse(n.Trim())).ToArray();

Thanks for the posting!

Write a comment