开发者

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

  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开发者_Go百科 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.


Rather that using the .ForEach extension method, you can just directly produce the results this way:

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

Or without using .Cast, like this:

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).

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.


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).

You need to use a Sub because there is nothing being returned from the expression:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜