abatishchev abatishchev - 11 days ago 6
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:

Foo(arr.Cast<int>.ToArray());


I can do next:

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


or

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


but both looks ugly.

Is there any other ways to complete the task?

Answer

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