C # string [] to int []

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

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

I tried using extension methods for the int class to add this function myself, but they do not become static.

Any idea on how to do this quickly and nicely?

+7
string arrays c # int parsing
source share
7 answers

This linq query should do this:

 strArray.Select(s => int.Parse(s)).ToArray() 
+17
source share
 int[] a = Array.ConvertAll("123,456".Split(','), s => Int32.Parse(s)); 

It should be good. You can change lambda to use TryParse if you don't want exceptions.

+8
source share
 int[] a = "123,456".Split(',').Select(s => int.Parse(s)).ToArray(); 
+6
source share
 "123,456".Split(',').Select( s => int.Parse(s) ).ToArray(); 
+3
source share

Use this:

 "123,456".Split(',').Select(s => int.Parse(s)).ToArray() 
+3
source share

I think like this:

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

Here is the extension method. This is done in a string because you cannot 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>(); } 

This is how you use it

 string testValue = "123, 456,789"; int[] testArray = testValue.ToIntArray(); 

It is assumed that you want to divide by ",", if not, then you need to change ToIntArray

+2
source share

All Articles