[英]Using LINQ's ForEach with anonymous methods 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
也许是这样的?
singles.ForEach(Function(s As [Single]) Do ???
如何使用匿名方法正确执行此操作(即不声明新函数)?
尝试这个:
singles.ForEach(Sub(s As [Single]) integers.Add(CInt(Math.Round(s))))
这里需要一个Sub
,因为For Each
循环的主体不返回值。
而是使用.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()
到上面代码示例的末尾。
如果希望内联表达式返回一个值,则可以使用Function。 例如:
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))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.