How to Convert string list to int list in C#

By FoxLearn 2/5/2025 9:26:24 AM   2
To convert a list of strings to a list of integers in C#, you can use several approaches.

Below are two common methods:

Using List.ConvertAll() with int.Parse()

ConvertAll(int.Parse) applies the int.Parse() method to each element of the stringList to convert it to an integer and returns a new list of integers.

For example:

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

List<int> intList = stringList.ConvertAll(int.Parse);

Console.WriteLine(string.Join(", ", intList));  // Output: 1, 2, 3

Using LINQ Select() with int.Parse()

Select(int.Parse) transforms each string in the list to an integer. Then, .ToList() converts the resulting IEnumerable<int> to a list.

For example:

using System.Linq;

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

List<int> intList = stringList.Select(int.Parse).ToList();

Console.WriteLine(string.Join(", ", intList));  // Output: 1, 2, 3

Handling Parsing Errors

If the string values might not always be valid integers, you can handle potential parsing errors by using int.TryParse() instead of int.Parse(). This way, invalid entries will be ignored or handled.

For example:

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

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

Console.WriteLine(string.Join(", ", intList));  // Output: 1, 3

int.TryParse() attempts to parse each string. If successful, it adds the result to intList; otherwise, it skips the invalid value (e.g., "abc").