1
What is a simple way to convert a string[] array to an integer array[]
string[] arrayString = new string[] {"10", "20", "30"}
To:
int[] arrayInt = new int[] {10, 20, 30}
1
What is a simple way to convert a string[] array to an integer array[]
string[] arrayString = new string[] {"10", "20", "30"}
To:
int[] arrayInt = new int[] {10, 20, 30}
1
A simple way to make this conversion is:
string[] arrayString = new string[] {"10", "20", "30"};
int[] arrayInt = arrayString.Select(int.Parse).ToArray();
Or
int[] arrayInt = arrayString.Select(lnq => int.Parse(lnq)).ToArray();
And in this way it is also possible to perform the conversion not only to int
, but also for decimal
, double
etc. ...
Just change inside the select "int. Parse" to the type you want to convert.
I know the question is yours and the answer worked for your case, but if the String array has letters beyond numbers it will give an exception. The correct thing is to use a tryParse
@Foci I agree with you just wanted to exemplify the case where I have a string array in which the array values are numbers and I want to convert them to a respective numerical array (int, double etc). But if inside the string array contains letters and the like. This top approach has to be modified.
0
You can do it like this:
int[] arrayInt1 = Array.ConvertAll(arrayString, x => int.Parse(x));
Or so:
int[] arrayInt1 = Array.ConvertAll(arrayString, int.Parse);
What this is different from the already posted answer?
The static method Array.Convertall
Did I do something wrong in the end? In my view it was just a supplementary answer. However, I will check the rules to avoid answers that are not appropriate.
Browser other questions tagged c# conversion
You are not signed in. Login or sign up in order to post.
Can you guarantee that all data is valid? Where are they coming from?
– Maniero
@Maniero This information where this information comes from and is valid is relevant ? For in my scenario the data came from a legacy basis and yes were valid.
– Sóstenes G. de Souza