gpt4 book ai didi

c# - 将逗号分隔的数字字符串转换为 List?

转载 作者:太空宇宙 更新时间:2023-11-03 17:33:55 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:




10年前关闭。




Possible Duplicate:
Split string, convert ToList<int>() in one line
Convert comma separated string of ints to int array



我有一个像这样的字符串: string test = "1,2,3,4";
有没有更简单的方法(语法上)将其转换为 List<int>相当于这样的东西:
string[] testsplit  = test.Split(',');
List<int> intTest = new List<int>();
foreach(string s in testsplit)
intTest.Add(int.Parse(s));

最佳答案

您可以将 LINQ 扔给它:

List<int> intTest = test.Split(',').Select(int.Parse).ToList();

它首先拆分字符串,然后解析每个部分(返回 IEnumerable<int>),最后从整数序列构造一个列表。

关于c# - 将逗号分隔的数字字符串转换为 List<int>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8749155/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com