Convert a string array to an int array in C#
This post will discuss how to convert a string array to an integer array in C#.
1. Using Array.ConvertAll() method
C# provides the Array.ConvertAll() method for converting an array of one type to another type. We can use it as follows to convert a string array to an integer array:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { string[] strings = new string[] {"1", "2", "3"}; int[] ints = Array.ConvertAll(strings, s => int.Parse(s)); Console.WriteLine(String.Join(",", ints)); } } |
We can improve the above code by using a method group in place of a lambda expression.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { string[] strings = new string[] {"1", "2", "3"}; int[] ints = Array.ConvertAll(strings, int.Parse); Console.WriteLine(String.Join(",", ints)); } } |
The int.Parse() method throws a FormatException if the string is not numeric. A better alternative is to call the Int32.TryParse() method. If the conversion operation fails, this method does not throw an exception and returns false. We can use this information to provide a default value when the conversion is failed for any member of the string array.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { string[] strings = new string[] {"X", "2", "3"}; int[] ints = Array.ConvertAll(strings, s => int.TryParse(s, out var x) ? x : -1); Console.WriteLine(String.Join(",", ints)); } } |
3. Using LINQ
We can also pass the int.Parse() method to LINQ’s Select() method and then call ToArray to get an array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Linq; public class Example { public static void Main() { string[] strings = new string[] {"1", "2", "3"}; int[] ints = strings.Select(int.Parse).ToArray(); Console.WriteLine(String.Join(",", ints)); } } |
That’s all about converting a string array to an int array 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 :)