我有一个字符串形式的整数数组:
var arr = new string[] { "1", "2", "3", "4" };
Run Code Online (Sandbox Code Playgroud)
我需要一个'真实'整数数组来推动它:
void Foo(int[] arr) { .. }
Run Code Online (Sandbox Code Playgroud)
我试图转换int,它当然失败了:
Foo(arr.Cast<int>.ToArray());
Run Code Online (Sandbox Code Playgroud)
我可以做下一个:
var list = new List<int>(arr.Length);
arr.ForEach(i => list.Add(Int32.Parse(i))); // maybe Convert.ToInt32() is better?
Foo(list.ToArray());
Run Code Online (Sandbox Code Playgroud)
要么
var list = new List<int>(arr.Length);
arr.ForEach(i =>
{
int j;
if (Int32.TryParse(i, out j)) // TryParse is faster, yeah
{
list.Add(j);
}
}
Foo(list.ToArray());
Run Code Online (Sandbox Code Playgroud)
但两个看起来都很难看.
还有其他方法可以完成任务吗?