在 VB.NET 中将 LINQ 的 ForEach 与匿名方法一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6015757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using LINQ's ForEach with anonymous methods in VB.NET
提问by serhio
I'm trying to replace the classic For Eachloop with the LINQ ForEachextension in VB.NET...
我正在尝试For Each用ForEachVB.NET 中的 LINQ扩展替换经典循环......
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)?
如何使用匿名方法(即不声明新函数)正确执行此操作?
回答by Daniel Hilgarth
Try this:
尝试这个:
singles.ForEach(Sub(s As [Single]) integers.Add(CInt(Math.Round(s))))
You need a Subhere, because the body of your For Eachloop doesn't return a value.
您需要一个Subhere,因为您的For Each循环体不返回值。
回答by Jeff B
Rather that using the .ForEachextension 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. If you want a List, simply tack on .ToList()to the end of the code samples above.
注意:这产生了一个IEnumerable(Of Integer)可以在大多数地方使用的地方你会使用List(Of Integer)... 但你不能添加到它。如果您想要List,只需添加.ToList()到上面代码示例的末尾即可。
回答by RichardW1001
You'd use a Function if you expect the inline expression to return a value. 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).
这将使用函数表达式,因为它的计算结果为布尔值 (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))))

