Split string, convert ToList<int>() in one line

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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(); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!