263

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

3
  • We had exactly the same question today: Click me Commented May 26, 2009 at 17:06
  • 3
    in "one line" si a very strong is a very strict requirement! </perl> Commented May 26, 2009 at 17:07
  • 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. Commented Mar 6, 2013 at 23:03

11 Answers 11

633
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

Sign up to request clarification or add additional context in comments.

5 Comments

This get Exception when the List has empty value or null.
@SayedM.Idrees just check null or empty before splitting.
add a null check: var numbers = sNumbers?.Split(',').Select(Int32.Parse).ToList();
Updated the answer to reflect null checks as mentioned by @MichaelG
How to convert it to List<long>? Select(Int64.Parse) is showing error.
46

Better use int.TryParse to avoid exceptions;

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

Comments

40

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

Comments

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

Comments

14

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

like this

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

Comments

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

Comments

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

Comments

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.

Comments

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

1 Comment

Thanks, although you declare a separator and then you don't use it.
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 _); 

Comments

-2

You can use this:

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

3 Comments

Welcome to Stack Overflow! While this code snippet may solve the question, including an explanation 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!
The function ConvertIntoIntList doesn't exits.
Also, you need to add the following class: static public class HelperMethods { static public List<int> ConvertIntoIntList(this string[] stringList) { int x = 0; var intList = stringList.Where(str => int.TryParse(str, out x)) .Select(str => x) .ToList(); return intList; } }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.