8

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?

George Johnston
  • 31,652
  • 27
  • 127
  • 172
Andreas
  • 201
  • 1
  • 3
  • 5

7 Answers7

18

This linq query should do it:

strArray.Select(s => int.Parse(s)).ToArray()
Oded
  • 489,969
  • 99
  • 883
  • 1,009
8
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
  • 9,994
  • 31
  • 47
  • 1
    `Array.ConvertAll` definitely requires fewer reallocations than LINQy `ToArray()`. Note that in this case, you don't even need a lambda, you can pass `Int32.Parse` as the second parameter of `ConvertAll`. – Ben Voigt May 08 '15 at 21:28
6
int[] a = "123,456".Split(’,’).Select(s => int.Parse(s)).ToArray();
bruno conde
  • 47,767
  • 15
  • 98
  • 117
3
”123,456”.Split(’,’).Select( s => int.Parse(s) ).ToArray();
Andrey
  • 59,039
  • 12
  • 119
  • 163
3

Use this :

"123,456".Split(',').Select(s => int.Parse(s)).ToArray()
Tomas Vana
  • 18,317
  • 9
  • 53
  • 64
3

I think, like that:

string[] sArr = { "1", "2", "3", "4" };
int[] res = sArr.Select(s => int.Parse(s)).ToArray();
ILya
  • 2,670
  • 4
  • 27
  • 40
2

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
  • 72,212
  • 42
  • 129
  • 156