Convert string array to int array C# in one line of code

Question:

How can you convert a string of space-separated numbers to an int array with one line of code?

I divided it into strings, but I don’t know how to convert this to an int array without creating an additional string array.

int [] Mas = textBox1.Text.Split(' ')

Answer:

Try the following

int[] a = textBox1.Text.Split(' ').Select(x => int.Parse(x)).ToArray();

It would be better to write

int[] a = textBox1.Text.Split(' ').
          Where(x => !string.IsNullOrWhiteSpace( x )).
          Select(x => int.Parse(x)).ToArray();
Scroll to Top