How to Convert comma separated string into a List ‘int’ ?

How to Convert comma separated string into a List<int> ?

Asked on October 26, 2018 in String.
Add Comment


  • 3 Answer(s)

    Use this code:

    List<int> TagIds = tags.Split(',').Select(int.Parse).ToList();
    
    Answered on October 26, 2018.
    Add Comment

    For the  inclusion of simple validation and skip over invalid values use the below code:

    string csv = "1,2,3,4,a,5";
    int mos = 0;
    var intList = csv.Split(',')
      .Select(m => { int.TryParse(m, out mos); return mos; })
      .Where(m => m != 0)
      .ToList();
    //returns a list with integers: 1, 2, 3, 4, 5
    
    Answered on October 26, 2018.
    Add Comment

       First, use the LINQ w/ int.Parse() to convert the string[] to the IEnumerable<int> and then it is easy to pass the result to the List<T> constructor:

    var tagIds = new List<int>(tags.Split(',').Select(s => int.Parse(s)));
    
    Answered on October 26, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.