Convert List of string to List of Int in C#
This post will discuss how to convert a List of String to a List of Int in C#.
We can use LINQ’s Select() method to convert List<string> to List<int> in C#. The Select() method projects each element of a sequence into a new form. The following code demonstrates its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string> { "1", "2", "3", "4" }; List<int> array = list.Select(int.Parse).ToList(); Console.WriteLine(String.Join(", ", array)); // 1, 2, 3, 4 } } |
Alternatively, you can use the List<T>.ConvertAll() method to convert a list of one type to another type. We can use it to convert a List of String to a List of Int as follows.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string> { "1", "2", "3", "4" }; List<int> array = list.ConvertAll(int.Parse); Console.WriteLine(String.Join(", ", array)); // 1, 2, 3, 4 } } |
That’s all about converting a List of String to a List of Int in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)