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

C#ListSplit

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Better use int.TryParse to avoid exceptions;

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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

like this

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

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

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.

Solution 9 - C#

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

Solution 10 - C#

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

Solution 11 - C#

You can use this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuzay95View Question on Stackoverflow
Solution 1 - C#mqpView Answer on Stackoverflow
Solution 2 - C#aozogulView Answer on Stackoverflow
Solution 3 - C#JozeView Answer on Stackoverflow
Solution 4 - C#yuxioView Answer on Stackoverflow
Solution 5 - C#Mukesh KalgudeView Answer on Stackoverflow
Solution 6 - C#Adrian FilipView Answer on Stackoverflow
Solution 7 - C#Pcodea XonosView Answer on Stackoverflow
Solution 8 - C#HyoJin KIMView Answer on Stackoverflow
Solution 9 - C#Carlos ToledoView Answer on Stackoverflow
Solution 10 - C#KabindasView Answer on Stackoverflow
Solution 11 - C#CharanjotView Answer on Stackoverflow