Convert List of Int to List of String in C#
This post will discuss how to convert List of Int to List of String in C#.
1. Using List<T>.ConvertAll()
method
The recommended approach to convert a list of one type to another type is using the List<T>.ConvertAll() method. It returns a list of the target type containing the converted elements from the current list. The following example demonstrates how to use the ConvertAll()
method to convert List<int>
to List<string>
.
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<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; List<string> strings = numbers.ConvertAll<string>(x => x.ToString()); Console.WriteLine(String.Join(", ", strings)); // 1, 2, 3, 4, 5 } } |
2. Using Enumerable.Select()
method
To convert a list of one type to a list of another type, you can apply a transform function to each element of the list. This can be easily achieved with LINQ’s Enumerable.Select() method, which projects each item of a sequence into a new form.
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<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; List<string> strings = numbers.Select(i => i.ToString()).ToList(); Console.WriteLine(String.Join(", ", strings)); // 1, 2, 3, 4, 5 } } |
That’s all about converting List of Int to List of String 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 :)