views:

1262

answers:

4

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?

+8  A: 

EDIT: to convert to array

int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();

This should do the trick:

var asIntegers = arr.Select(s => int.Parse(s));
Simon Fox
.ToArray() required to satisfy OP's question
spender
change var to int[] and append .ToArray() if you need it as an int array
Simon Fox
+1  A: 
var list = arr.Select(i => Int32.Parse(i));
sepp2k
+2  A: 
var asIntegers = arr.Select(s => int.Parse(s)).ToArray();

Have to make sure you are not getting an IEnumerable<int> as a return

Rob
+25  A: 

You can use the Array.ConvertAll method:

int[] myInts = Array.ConvertAll(arr, s => Int32.Parse(s));
Ahmad Mageed
Nice. Didn't know that one. +1
spender
+1 for smallest footprint, even though LINQ is asked
Marc
More reader-friendly +1
Havenard
The IL code this generates is actually less than Simon Fox's answer, FWIW
Allen