可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a string that has numbers
string sNumbers = "1,2,3,4,5";
I can split it then convert it to List
sNumbers.Split( new[] { ',' } ).ToList();
How can I convert string array to integer list? So that I'll be able to convert string[]
to IEnumerable
回答1:
var numbers = sNumbers.Split(',').Select(Int32.Parse).ToList();
回答2:
You can also do it this way without the need of Linq:
List numbers = new List( Array.ConvertAll(sNumbers.Split(','), int.Parse) ); // Uses Linq var numbers = Array.ConvertAll(sNumbers.Split(','), int.Parse).ToList();
回答3:
Joze's way also need LINQ, ToList()
is in System.Linq
namespace.
You can convert Array to List without Linq by passing the array to List constructor:
List numbers = new List( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
回答4:
On Unity3d, int.Parse
doesn't work well. So I use like bellow.
List intList = new List( Array.ConvertAll(sNumbers.Split(','), new Converter((s)=>{return Convert.ToInt32(s);}) ) );
Hope this help for Unity3d Users.
回答5:
also you can use this Extension method
public static List SplitToIntList(this string list, char separator = ',') { return list.Split(separator).Select(Int32.Parse).ToList(); }
usage:
var numberListString = "1, 2, 3, 4"; List numberList = numberListString.SplitToIntList(',');
回答6:
It is also possible to int array to direct assign value.
like this
int[] numbers = sNumbers.Split(',').Select(Int32.Parse).ToArray();
回答7:
My problem was similar but with the inconvenience that sometimes the string contains letters (sometimes empty).
string sNumbers = "1,2,hh,3,4,x,5";
Trying to follow Pcode Xonos Extension Method:
public static List SplitToIntList(this string list, char separator = ',') { int result = 0; return (from s in list.Split(',') let isint = int.TryParse(s, out result) let val = result where isint select val).ToList(); }
回答8:
You can use new C# 6.0 Language Features:
- replace delegate
(s) => { return Convert.ToInt32(s); }
with corresponding method group Convert.ToInt32
- replace redundant constructor call:
new Converter(Convert.ToInt32)
with: Convert.ToInt32
The result will be:
var intList = new List(Array.ConvertAll(sNumbers.Split(','), Convert.ToInt32));
回答9:
You can use this:
List sNumberslst = sNumbers.Split(',').ConvertIntoIntList();