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

时间:2011-05-16 10:02:27

标签: .net vb.net linq for-loop foreach

我正在尝试用VB.NET中的LINQ For Each扩展替换经典的ForEach循环...

  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 ???

如何使用匿名方法正确执行此操作(即不声明新功能)?

3 个答案:

答案 0 :(得分:21)

试试这个:

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

这里需要Sub,因为For Each循环的正文不会返回值。

答案 1 :(得分:4)

而是使用.ForEach扩展方法,您可以直接以这种方式生成结果:

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

或者不使用.Cast,就像这样:

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

它使您不必预先确定List(Of Integer),我还认为您只是应用转换并生成结果(从分配中可以清楚地看出)更清楚。

注意:这会生成一个IEnumerable(Of Integer),可以在大多数使用List(Of Integer)的地方使用...但是您无法添加它。如果您需要List,只需将.ToList()添加到上面代码示例的末尾。

答案 2 :(得分:1)

如果希望内联表达式返回值,则可以使用函数。例如:

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

这会使用一个Function表达式,因为它的值是布尔值(p.Id = 1)。

您需要使用Sub,因为表达式中没有返回任何内容:

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