[英]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. 我正在尝试使用包含逗号分隔数字列表的字符串初始化int数组。
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'
无法将类型'string'隐式转换为'int'
How to convert string into sequence of integers? 如何将字符串转换为整数序列?
You want one line? 你要一行吗? Use LINQ:
使用LINQ:
int[] cols = sizes.Split(',').Select(x => int.Parse(x)).ToArray();
Add using System.Linq;
using System.Linq;
添加using System.Linq;
at the top of the file to make it work. 使其位于文件顶部。
Without LINQ you'd need a loop: 没有LINQ,您将需要循环:
var source = sizes.Split(',');
var cols = new int[source.Length];
for(int i = 0; i < source.Length; i++)
{
cols[i] = int.Parse(source[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.