How to Convert string list to int list in C#
By FoxLearn 3/4/2025 2:59:54 AM 230
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, list c# convert string
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"
).
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#