[c#] Split string, convert ToList<int>() in one line

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

This question is related to c# list split

The answer is


Better use int.TryParse to avoid exceptions;

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

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

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

You can use this:

List<Int32> sNumberslst = sNumbers.Split(',').ConvertIntoIntList();

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.


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

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

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(',');

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

like this

int[] numbers = sNumbers.Split(',').Select(Int32.Parse).ToArray();

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows