views:

176

answers:

7

Is there a way to convert string arrays to int arrays as easy as parsing an string to an int in C#.

int a = int.Parse(”123”);
int[] a = int.Parse(”123,456”.Split(’,’)); // this don't work.

I have tried using extension methods for the int class to add this functionality myself but they don't become static.

Any idea on how to do this fast and nice?

+10  A: 

This linq query should do it:

strArray.Select(s => int.Parse(s)).ToArray()
Oded
+6  A: 
int[] a = Array.ConvertAll("123,456".Split(','), s => Int32.Parse(s));

Should do just fine. You could modify the lambda to use TryParse if you don't want exceptions.

Ron Warholic
+2  A: 
”123,456”.Split(’,’).Select( s => int.Parse(s) ).ToArray();
Andrey
+4  A: 
int[] a = "123,456".Split(’,’).Select(s => int.Parse(s)).ToArray();
bruno conde
+2  A: 

Use this :

"123,456".Split(',').Select(s => int.Parse(s)).ToArray()
Thomas Wanner
+2  A: 

I think, like that:

string[] sArr = { "1", "2", "3", "4" };
int[] res = sArr.Select(s => int.Parse(s)).ToArray();
ILya
+1  A: 

Here is the extension method. This is done on string, because you can't add a static function to a string.

public static int[] ToIntArray(this string value)
{
    return value.Split(',')
        .Select<string, int>(s => int.Parse(s))
        .ToArray<int>();
}

Here is how you use it

string testValue = "123, 456,789";

int[] testArray = testValue.ToIntArray();

This assumes you want to split on ',' if not then you have to change the ToIntArray

David Basarab
Very awesome, just what I was looking for. Thanks!
Refracted Paladin