C# – Convert string list to int list

You can convert a list of strings to a list of integers by using int.Parse() on all of the strings. There are two simple ways to do this:

  • Use List.ConvertAll() with int.Parse().
  • Use Select() with int.Parse().

I’ll show examples of these using these methods and then explain how to handle parsing exceptions.

Option 1 – Use List.ConvertAll()

Here’s an example of how to use List.ConvertAll() with int.Parse() to convert a list of strings to ints:

var stringList = new List<string>()
{
    "0","1","2"
};

List<int> intList = stringList.ConvertAll(int.Parse);
Code language: C# (cs)

ConvertAll() loops over the strings and uses int.Parse() to convert each string to an integer. It returns the integers in a new list. This is faster than Select() for small input and slightly faster for larger input (> 5000 elements).

Option 2 – Use Select() + int.Parse()

Here’s an example of using the Linq Select() method with int.Parse() to convert a list of strings to a list of integers.

using System.Linq;

var stringList = new List<string>()
{
    "0","1","2"
};

List<int> intList = stringList.Select(int.Parse).ToList();
Code language: C# (cs)

The Select() returns an IEnumerable<int>, so use ToList() to convert this back to a list.

Handling parsing exceptions

When you use int.Parse() with ConvertAll() or Select(), it’s an all-or-nothing process. int.Parse() throws exceptions when the string can’t be converted. This happens for three main reasons:

  • The string is null (ArgumentNullException).
  • The string isn’t a valid integer (FormatException).
  • The string value is > int.MaxValue or < int.MinValue (OverflowException).

One option is to filter out the invalid input. The simplest way to do that is by using int.TryParse() in a loop. This gives you an int (if parsing succeeded), which you can then add to the list. Here’s an example:

var stringList = new List<string>()
{
    "abc", "1", "2", "3"
};

var intList = new List<int>(stringList.Count);

foreach(var s in stringList)
{
    if (int.TryParse(s, out int result))
        intList.Add(result);
}

Console.WriteLine(string.Join(",", intList));
Code language: C# (cs)

This outputs the following valid integers:

1,2,3Code language: plaintext (plaintext)

If you’re getting OverflowExceptions and want to be able to parse the big integers, you can use a larger type such as long (64-bit). Here’s an example of using ConvertAll() with long.Parse():

List<string> stringList = new List<string>()
{
    "1", "2",
    "9223372036854775807"
};

List<long> intList = stringList.ConvertAll(long.Parse);
Code language: C# (cs)