简体   繁体   English

在VB.NET中使用LINQ的ForEach和匿名方法

[英]Using LINQ's ForEach with anonymous methods in VB.NET

I'm trying to replace the classic For Each loop with the LINQ ForEach extension in VB.NET... 我正在尝试用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

Maybe something like this? 也许是这样的?

  singles.ForEach(Function(s As [Single]) Do ???

How can I correctly do this using anonymous methods (ie without declare a new function)? 如何使用匿名方法正确执行此操作(即不声明新函数)?

Try this: 尝试这个:

singles.ForEach(Sub(s As [Single]) integers.Add(CInt(Math.Round(s))))

You need a Sub here, because the body of your For Each loop doesn't return a value. 这里需要一个Sub ,因为For Each循环的主体不返回值。

Rather that using the .ForEach extension method, you can just directly produce the results this way: 而是使用.ForEach扩展方法,您可以直接以这种方式生成结果:

Dim integers = singles.Select(Function(x) Math.Round(x)).Cast(Of Integer)()

Or without using .Cast , like this: 或者不使用.Cast ,像这样:

Dim integers = singles.Select(Function(x) CInt(Math.Round(x)))

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). 它使您不必预先确定List(Of Integer) ,我还认为您只是应用转换并生成结果(从赋值中可以清楚地看出)更清楚。

Note: this produced an IEnumerable(Of Integer) which can be used most places where you'd use a List(Of Integer) ... but you can't add to it. 注意:这产生了一个IEnumerable(Of Integer) ,它可以用在你使用List(Of Integer)大多数地方......但你不能添加它。 If you want a List , simply tack on .ToList() to the end of the code samples above. 如果你想要一个List ,只需将.ToList()到上面代码示例的末尾。

You'd use a Function if you expect the inline expression to return a value. 如果希望内联表达式返回一个值,则可以使用Function。 For example: 例如:

Dim myProduct = repository.Products.First(Function(p) p.Id = 1)

This would use a Function expression, because it's something that evaluates to a Boolean (p.Id = 1). 这将使用一个Function表达式,因为它的值是一个布尔值(p.Id = 1)。

You need to use a Sub because there is nothing being returned from the expression: 您需要使用Sub,因为表达式中没有返回任何内容:

singles.ForEach(Sub(s) integers.Add(CInt(Math.Round(s))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM