How to Convert string list to int list in C#
By FoxLearn 2/5/2025 9:26:24 AM 2
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"
).
- String to Byte Array Conversion in C#
- How to Trim a UTF-8 string to the specified number of bytes in C#
- How to Save a list of strings to a file in C#
- How to Convert string list to float list in C#
- How to Remove a list of characters from a string in C#
- How to Check if a string contains any substring from a list in C#
- Find a character in a string in C#
- Remove non-alphanumeric characters from a string in C#