Split string, convert ToList() in one line

后端 未结 10 1895
借酒劲吻你
借酒劲吻你 2020-11-27 10:00

I have a string that has numbers

string sNumbers = \"1,2,3,4,5\";

I can split it then convert it to List

         


        
相关标签:
10条回答
  • 2020-11-27 10:42

    also you can use this Extension method

    public static List<int> SplitToIntList(this string list, char separator = ',')
    {
        return list.Split(separator).Select(Int32.Parse).ToList();
    }
    

    usage:

    var numberListString = "1, 2, 3, 4";
    List<int> numberList = numberListString.SplitToIntList(',');
    
    0 讨论(0)
  • 2020-11-27 10:46

    It is also possible to int array to direct assign value.

    like this

    int[] numbers = sNumbers.Split(',').Select(Int32.Parse).ToArray();
    
    0 讨论(0)
  • 2020-11-27 10:48

    On Unity3d, int.Parse doesn't work well. So I use like bellow.

    List<int> intList = new List<int>( Array.ConvertAll(sNumbers.Split(','),
     new Converter<string, int>((s)=>{return Convert.ToInt32(s);}) ) );
    

    Hope this help for Unity3d Users.

    0 讨论(0)
  • 2020-11-27 10:51

    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<int> 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(); 
    }
    
    0 讨论(0)
提交回复
热议问题