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

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();
Posted on by Joe in C#, Linq

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

  1. Mark

    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!

Add a Comment