How to convert a string array[] to an integer array int[]

Asked

Viewed 993 times

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}
  • 2

    Can you guarantee that all data is valid? Where are they coming from?

  • @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.

2 answers

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.

  • 1

    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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.