我正在尝试实施Map
在 VB.NET 中,具有所描述的功能在这个答案中。 https://stackoverflow.com/questions/749084/jquery-map-vs-each
应该需要一个IEnumerable(Of TIn)
and a Function(Of TIn, TOut)
,对每个元素执行该函数,并返回new IEnumerable(Of TOut)
.
我知道 VB.NET 不是真正的函数式语言。我有业务需求,但仍然想使用一些功能花絮,尤其是与 LINQ 结合使用。
类似的问题被问到here https://stackoverflow.com/questions/9096830/map-function-in-vb-net,但问题和答案实际上是关于实施Each
.
谢谢@Sehnsucht https://stackoverflow.com/users/4925216/sehnsucht指出有已经是一个Map
功能在 LINQ 中称为Select https://msdn.microsoft.com/en-us/library/bb548891%28v=vs.110%29.aspx.
这是我最初的答案,绝对不如设计 LINQ 的聪明人创建的答案:
这是一个扩展方法,可以放置在Module
在根命名空间中:
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)
因为它对我的目的更有用(而且,它返回一个列表!)。它可能会返回一个IEnumerable(Of TOut)
通过将返回行更改为Return l.AsEnumerable()
。它接受一个IEnumerable(Of TIn)
而不是IList(Of TIn)
因此它可以接受更广泛的输入。
我对任何提出性能改进建议的人持开放态度。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)