Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String[] to int[] in C# and .NET 2.0?

Tags:

c#

.net-2.0

I've got :

string[] strArray = new string[3] { "1", "2", "12" };

And I want something like this

int[] intArray = Convert.toIntArray(strArray);

I work int C# .net v2.0, I don't want to write a lot of code.

How can I do that?

Thank you.

like image 623
Christophe Debove Avatar asked Dec 08 '10 13:12

Christophe Debove


4 Answers

You can use the Array.ConvertAll method for this purpose, which "converts an array of one type to an array of another type."

int[] intArray = Array.ConvertAll(strArray,
                                  delegate(string s) { return int.Parse(s); });

(EDIT: Type-inference works fine with this technique. Alternatively, you could also use an implicit method-group conversion as in Marc Gravell's answer, but you would have to specify the generic type-arguments explicitly.)

Using a for-loop:

int[] intArray = new int[strArray.Length];

for (int i = 0; i < strArray.Length; i++)
   intArray[i] = int.Parse(strArray[i]);

For completeness, the idiomatic way of doing this in C# 4.0 would be something like:

var intArray = strArray.Select(int.Parse).ToArray();

or:

//EDIT: Probably faster since a fixed-size buffer is used
var intArray = Array.ConvertAll(strArray, int.Parse);
like image 134
Ani Avatar answered Dec 10 '22 13:12

Ani


int[] intArray = Array.ConvertAll(strArray, int.Parse);

or in C# 2.0 (where the generic type inference is weaker):

int[] intArray = Array.ConvertAll<string,int>(strArray, int.Parse);
like image 30
Marc Gravell Avatar answered Dec 10 '22 13:12

Marc Gravell


using System.Collections.Generic;

int Convert(string s)
{
    return Int32.Parse(s);
}

int[] result = Array.ConvertAll(input, new Converter<string, int>(Convert));

or

int[] result = Array.ConvertAll(input, delegate(string s) { return Int32.Parse(s); })
like image 45
abatishchev Avatar answered Dec 10 '22 13:12

abatishchev


Array.ConvertAll Generic Method

Converts an array of one type to an array of another type.

like image 41
CD.. Avatar answered Dec 10 '22 11:12

CD..