I've got :
string[] strArray = new string[3] { "1", "2", "12" };
And I want something like this
int[] intArray = Convert.toIntA开发者_StackOverflow中文版rray(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.
When you are sure, all items are definitely parsable, this will do the trick:
string[] strArray = new string[3] { "1", "2", "12" };
int[] intArray = new int[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
intArray[i] = int.Parse(strArray[i]);
}
Something like this, but you want to keep a bit of error checking ( my if is really lame, just as example ):
static private int[] toIntArray(string[] strArray)
{
int[] intArray = new int[strArray.Length];
for (int index = 0; index < strArray.Length; index++)
{
intArray[index] = Int32.Parse(strArray[index]);
}
return intArray;
}
And use it like this:
string[] strArray = new string[3] { "1", "2", "12" };
int[] interi = toIntArray(strArray);
精彩评论