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?
Given an array you can use the
Array.ConvertAll
method:Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
A LINQ solution is similar, except you would need the extra
ToArray
call to get an array:EDIT: to convert to array
This should do the trick:
To avoid exceptions with
.Parse
, here are some.TryParse
alternatives.To use only the elements that can be parsed:
or
Alternatives using
0
for the elements that can't be parsed:or
C# 7.0:
Have to make sure you are not getting an
IEnumerable<int>
as a returnyou can simply cast a string array to int array by: