gpt4 book ai didi

vb.net - 如何在VB.NET中实现 map 功能

转载 作者:行者123 更新时间:2023-12-02 06:57:52 25 4
gpt4 key购买 nike

我正在尝试在 VB.NET 中实现 Map 并具有描述的功能 in this answer.

它应该采用一个 IEnumerable(Of TIn) 和一个 Function(Of TIn, TOut),对每个元素执行该函数,并返回一个 new IEnumerable(Of TOut)

我知道 VB.NET 不是真正的函数式语言。我有业务需求,但仍然想使用一些功能花絮,尤其是与 LINQ 结合使用。

提出了类似的问题here ,但问题和答案实际上是关于实现 Each

最佳答案

感谢 @Sehnsucht指出 LINQ 中已经有一个 Map 函数,名为 Select .

这是我最初的答案,它绝对不如设计 LINQ 的聪明人创建的答案:

这是一个可以放置在根命名空间中的模块中的扩展方法:

Module Extensions
<System.Runtime.CompilerServices.Extension> _
Public Function Map(Of TIn, TOut)(ByVal a As IEnumerable(Of TIn), ByVal f As Func(Of TIn, TOut)) As IList(Of TOut)
Dim l As New List(Of TOut)
For Each i As TIn In a
Dim x = f(i)
l.Add(x)
Next
Return l
End Function
End Module

可以这样调用:

Sub Main()
Dim Test As New List(Of Double) From {-10000000, -1, 1, 1000000}
Dim Result1 = Test.Map(Function(x) x.ToString("F2"))
'Result1 is of type IList(Of String)
Dim Result2 = Test.Map(AddressOf IsPositive)
'Result2 is of type IList(Of Boolean)
Dim Result3 = Map(Test, Function(y) y + 1)
'Result3 is of type IList(Of Double)
End Sub

Private Function IsPositive(d As Double) As Boolean
If d > 0 then
Return True
Else
Return False
End If
End Function

我返回一个IList(Of TOut),因为它对我的目的更有用(而且,它返回一个列表!)。通过将返回行更改为 Return l.AsEnumerable(),它可以返回 IEnumerable(Of TOut)。它接受 IEnumerable(Of TIn) 而不是 IList(Of TIn),因此它可以接受更广泛的输入。

我对任何提出性能改进建议的人持开放态度。

关于vb.net - 如何在VB.NET中实现 map 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31008744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com