Coder Perfect

In one line, split the string and convert ToListint>().

Problem

I’ve got a number-filled string.

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

I can break it into two parts and then convert it to a Listint>.

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

What is the best way to convert a string array to an integer list? So that I may convert a string[] to an IEnumerable

Asked by uzay95

Solution #1

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

Answered by mqp

Solution #2

To avoid exceptions, use int.TryParse instead.

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

Answered by aozogul

Solution #3

You may also do it this way if you don’t want to use Linq:

List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );

// Uses Linq
var numbers = Array.ConvertAll(sNumbers.Split(','), int.Parse).ToList();

Answered by Joze

Solution #4

Joze’s method also requires LINQ, as ToList() is found in System. Namespace for Linq.

Without using Linq, you can convert an array to a list by providing it to the List constructor:

List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );

Answered by yuxio

Solution #5

It is also possible to assign a value directly to an int array.

like this

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

Answered by Mukesh Kalgude

Post is based on https://stackoverflow.com/questions/911717/split-string-convert-tolistint-in-one-line