转换的String []为int []在一条线的使用LINQ code一条线、int、String、LINQ

2023-09-02 10:17:52 作者:枯守一座城

我有一个整数的字符串形式的数组:

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());

我可以做下一个:

I can do next:

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());

但无论长相丑陋。

but both looks ugly.

有没有其他的方法来完成任务?

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));

感谢马克Gravell的指出了拉姆达可以省略,产生一个较短的版本如下:

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();