简体   繁体   中英

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?

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM