Split string, convert ToList() in one line

后端 未结 10 1865
借酒劲吻你
借酒劲吻你 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:26
    var numbers = sNumbers.Split(',').Select(Int32.Parse).ToList();
    
    0 讨论(0)
  • 2020-11-27 10:30

    You can also do it this way without the need of Linq:

    List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
    
    // Uses Linq
    var numbers = Array.ConvertAll(sNumbers.Split(','), int.Parse).ToList();
    
    0 讨论(0)
  • 2020-11-27 10:30

    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<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
    
    0 讨论(0)
  • 2020-11-27 10:35

    You can use this:

    List<Int32> sNumberslst = sNumbers.Split(',').ConvertIntoIntList();
    
    0 讨论(0)
  • 2020-11-27 10:37

    Better use int.TryParse to avoid exceptions;

    var numbers = sNumbers
                .Split(',')
                .Where(x => int.TryParse(x, out _))
                .Select(int.Parse)
                .ToList();
    
    0 讨论(0)
  • 2020-11-27 10:37

    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<string, int>(Convert.ToInt32) with: Convert.ToInt32

    The result will be:

    var intList = new List<int>(Array.ConvertAll(sNumbers.Split(','), Convert.ToInt32));
    
    0 讨论(0)
提交回复
热议问题