将逗号分隔的整数列表转换为数组 [英] Convert comma separated list of integers into an array

查看:63
本文介绍了将逗号分隔的整数列表转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用包含逗号分隔数字列表的字符串初始化int数组。

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

但显然失败了:


无法将类型'string'隐式转换为'int'

cannot implicitly convert type 'string' to 'int'

如何将字符串转换为整数序列? / p>

How to convert string into sequence of integers?

推荐答案

您要一行吗?使用LINQ:

You want one line? Use LINQ:

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

使用System.Linq添加

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

没有LINQ,您需要循环:

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

这篇关于将逗号分隔的整数列表转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆