给定一个字符串数组,比如说:Dim array1 As String() = {"1", "2", "3"}复制该数组并对每个元素执行操作的最佳方法是什么?
换句话说,复制该数组的最佳方法是: array2 as integer() = {1, 2, 3}
例如,类似于JavaScript的.Map函数:
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
// Result: 2, 3, 4, 5
Run Code Online (Sandbox Code Playgroud)
如果不可能在一行 - 我怀疑它不是 - 你最快的选择是什么?谢谢!
如果你不想使用任何LINQ扩展方法,但你可以使用lambda表达式,你仍然可以使用Array.ConvertAll以下方法在一行中完成:
Dim input() As String = {"1", "2", "3"}
Dim output() As Integer = Array.ConvertAll(input, Function(x) Integer.Parse(x))
Run Code Online (Sandbox Code Playgroud)
但是,它确实提出了一个问题:为什么不在这一点上使用LINQ,因为它实际上是相同的:
Dim input() As String = {"1", "2", "3"}
Dim output() As Integer = input.Select(Function(x) Integer.Parse(x)).ToArray()
Run Code Online (Sandbox Code Playgroud)
我想补充一点,与 JavaScript 类似,.NET 的映射等效项Select也支持方法组以及 lambda。
这是一个使用 lambda 的示例:
Dim output = input.Select(Function(x) SomeMethod(x)).ToArray()
Run Code Online (Sandbox Code Playgroud)
这是使用方法组的示例。由于方法调用的括号在 VB.NET 中是可选的,因此AddressOf需要附加关键字:
Dim output = input.Select(AddressOf SomeMethod).ToArray()
Run Code Online (Sandbox Code Playgroud)
为了完整起见,这里有一个使用 LINQ 查询语法的示例,它只是第一个示例的语法糖:
Dim output = (From x In input Select SomeMethod(x)).ToArray()
Run Code Online (Sandbox Code Playgroud)