在 VB.NET 中使用 LINQ 的 ForEach 和匿名方法
我正在尝试用 VB.NET 中的 LINQ ForEach
扩展替换经典的 For Each
循环...
Dim singles As New List(Of Single)(someSingleList)
Dim integers As New List(Of Integer)
For Each singleValue In singles
integers.Add(CInt(Math.Round(singleValue)))
Next singleValue
也许是这样的?
singles.ForEach(Function(s As [Single]) Do ???
我怎样才能使用匿名方法正确地做到这一点(即不声明新函数)?
I'm trying to replace the classic For Each
loop with the LINQ ForEach
extension in VB.NET...
Dim singles As New List(Of Single)(someSingleList)
Dim integers As New List(Of Integer)
For Each singleValue In singles
integers.Add(CInt(Math.Round(singleValue)))
Next singleValue
Maybe something like this?
singles.ForEach(Function(s As [Single]) Do ???
How can I correctly do this using anonymous methods (i.e. without declare a new function)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
这里需要一个
Sub
,因为For Each
循环的主体不返回值。Try this:
You need a
Sub
here, because the body of yourFor Each
loop doesn't return a value.您可以不使用
.ForEach
扩展方法,而是直接以这种方式生成结果:或者不使用
.Cast
,如下所示:它使您无需预先声明
List(Of Integer)
而且我还认为更清楚的是,您只是应用转换并生成结果(从作业中可以清楚地看出)。注意:这产生了一个
IEnumerable(Of Integer)
,它可以在大多数使用List(Of Integer)
的地方使用......但你不能添加到它。如果您想要一个List
,只需将.ToList()
添加到上面代码示例的末尾即可。Rather that using the
.ForEach
extension method, you can just directly produce the results this way:Or without using
.Cast
, like this:It saves you from having to predeclare the
List(Of Integer)
and I also think it is clearer that you are simply applying a transformation and producing a result (which is clear from the assignment).Note: this produced an
IEnumerable(Of Integer)
which can be used most places where you'd use aList(Of Integer)
... but you can't add to it. If you want aList
, simply tack on.ToList()
to the end of the code samples above.如果您希望内联表达式返回一个值,则可以使用函数。例如:
这将使用函数表达式,因为它的计算结果为布尔值 (p.Id = 1)。
您需要使用 Sub,因为表达式没有返回任何内容:
You'd use a Function if you expect the inline expression to return a value. For example:
This would use a Function expression, because it's something that evaluates to a Boolean (p.Id = 1).
You need to use a Sub because there is nothing being returned from the expression: