abatishchev abatishchev - 2 months ago 24
C# Question

Convert string[] to int[] in one line of code using LINQ

I have an array of integers in string form:

var arr = new string[] { "1", "2", "3", "4" };

I need to an array of 'real' integers to push it further:

void Foo(int[] arr) { .. }

I tried to cast int and it of course failed:


I can do next:

var list = new List<int>(arr.Length);
arr.ForEach(i => list.Add(Int32.Parse(i))); // maybe Convert.ToInt32() is better?


var list = new List<int>(arr.Length);
arr.ForEach(i =>
int j;
if (Int32.TryParse(i, out j)) // TryParse is faster, yeah

but both looks ugly.

Is there any other ways to complete the task?


Given an array you can use the Array.ConvertAll method:

int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));

Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:

int[] myInts = Array.ConvertAll(arr, int.Parse);

A LINQ solution is similar, except you would need the extra ToArray call to get an array:

int[] myInts = arr.Select(int.Parse).ToArray();