Search code examples
c#arraysinitialization

Convert comma separated list of integers into an array


I'm trying to initialize an int array with a string that contains list of comma separated numbers.

I tried to directly assign string to array,

string sizes = "2,10,65,10"; 
int[] cols = new int[] { sizes };

but it obviously fails:

cannot implicitly convert type 'string' to 'int'

How to convert string into sequence of integers?


Solution

  • You want one line? Use LINQ:

    int[] cols = sizes.Split(',').Select(x => int.Parse(x)).ToArray();
    

    Add using System.Linq; at the top of the file to make it work.

    Without LINQ you'd need a loop:

    var source = sizes.Split(',');
    var cols = new int[source.Length];
    for(int i = 0; i < source.Length; i++)
    {
        cols[i] = int.Parse(source[i]);
    }