248

I have a string that has numbers

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

I can split it then convert it to List<int>

sNumbers.Split( new[] { ',' } ).ToList<int>();

How can I convert string array to integer list? So that I'll be able to convert string[] to IEnumerable

Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
uzay95
  • 16,052
  • 31
  • 116
  • 182
  • 3
    in "one line" si a very strong is a very strict requirement! – dfa May 26 '09 at 17:07
  • We had exactly the same question today: [Click me](http://stackoverflow.com/questions/910119/how-to-create-a-listt-from-a-comma-seperated-string) – Dario May 26 '09 at 17:06
  • 2
    This question specifically says to split a string of numbers, which keeps the answer simple. The question Dario mentioned handles (bogs down in?) issues of TryParse for general strings. – goodeye Mar 06 '13 at 23:03

11 Answers11

608
var numbers = sNumbers?.Split(',')?.Select(Int32.Parse)?.ToList();

Recent versions of C# (v6+) allow you to do null checks in-line using the null-conditional operator

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
mqp
  • 70,359
  • 14
  • 95
  • 123
41

Better use int.TryParse to avoid exceptions;

var numbers = sNumbers
            .Split(',')
            .Where(x => int.TryParse(x, out _))
            .Select(int.Parse)
            .ToList();
aozogul
  • 571
  • 5
  • 8
39

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();
Jose Luis
  • 3,307
  • 3
  • 36
  • 53
20

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) );
yuxio
  • 351
  • 2
  • 6
13

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

like this

int[] numbers = sNumbers.Split(',').Select(Int32.Parse).ToArray();
Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32
6

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));
Adrian Filip
  • 61
  • 2
  • 2
4

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(',');
Pcodea Xonos
  • 161
  • 1
  • 6
3

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.

HyoJin KIM
  • 402
  • 8
  • 17
2

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(); 
}
Carlos Toledo
  • 2,519
  • 23
  • 23
1

Why stick with just int when we have generics? What about an extension method like :

    public static List<T> Split<T>(this string @this, char separator, out bool AllConverted)
    {
        List<T> returnVals = new List<T>();
        AllConverted = true;
        var itens = @this.Split(separator);
        foreach (var item in itens)
        {
            try
            {
                returnVals.Add((T)Convert.ChangeType(item, typeof(T)));
            }
            catch { AllConverted = false; }
        }
        return returnVals;
    }

and then

 string testString = "1, 2, 3, XP, *, 6";
 List<int> splited = testString.Split<int>(',', out _);
Kabindas
  • 802
  • 9
  • 6
-2

You can use this:

List<Int32> sNumberslst = sNumbers.Split(',').ConvertIntoIntList();
Seth
  • 1,545
  • 1
  • 16
  • 30
Charanjot
  • 7
  • 1
  • 2
    Welcome to Stack Overflow! While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Aug 01 '16 at 08:58
  • 2
    The function ConvertIntoIntList doesn't exits. – Federico Navarrete Jun 12 '18 at 10:59
  • Also, you need to add the following class: static public class HelperMethods { static public List ConvertIntoIntList(this string[] stringList) { int x = 0; var intList = stringList.Where(str => int.TryParse(str, out x)) .Select(str => x) .ToList(); return intList; } } – Federico Navarrete Jun 15 '18 at 06:24