使用 LINQ 在一行代码中将 string[] 转换为 int[]
问题描述:
我有一个字符串形式的整数数组:
I have an array of integers in string form:
var arr = new string[] { "1", "2", "3", "4" };
我需要一个真实"整数数组来进一步推动它:
I need to an array of 'real' integers to push it further:
void Foo(int[] arr) { .. }
我尝试转换 int 并且它当然失败了:
I tried to cast int and it of course failed:
Foo(arr.Cast<int>.ToArray());
接下来我可以做:
var list = new List<int>(arr.Length);
arr.ForEach(i => list.Add(Int32.Parse(i))); // maybe Convert.ToInt32() is better?
Foo(list.ToArray());
或
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());
但两者都看起来很丑.
还有其他方法可以完成任务吗?
Is there any other ways to complete the task?
答
给定一个数组,您可以使用 Array.ConvertAll
方法:
Given an array you can use the Array.ConvertAll
method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
感谢 Marc Gravell 指出可以省略 lambda,从而生成如下所示的较短版本:
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
LINQ 解决方案类似,只是您需要额外的 ToArray
调用来获取数组:
A LINQ solution is similar, except you would need the extra ToArray
call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();