How to Convert string list to int list in C#
By FoxLearn 3/25/2025 1:37:42 AM 312
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, string c# join list
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"
).
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization
- The JSON value could not be converted to Enum