相关疑难解决方法(0)

使用LINQ在一行代码中将string []转换为int []

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

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)

但两个看起来都很难看.

还有其他方法可以完成任务吗?

.net c# linq extension-methods

253
推荐指数
4
解决办法
21万
查看次数

标签 统计

.net ×1

c# ×1

extension-methods ×1

linq ×1