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.
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);
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);
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); })
Array.ConvertAll Generic Method
Converts an array of one type to an array of another type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With