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

Viewed 257981

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

11 Answers
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

Better use int.TryParse to avoid exceptions;

var numbers = sNumbers
            .Split(',')
            .Where(x => int.TryParse(x, out _))
            .Select(int.Parse)
            .ToList();

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

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 _);
Related