Dot-Net

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

  • August 18, 2013

我正在嘗試用VB.NET 中For Each的 LINQ 擴展替換經典循環…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 ???

如何使用匿名方法(即不聲明新函式)正確地做到這一點?

嘗試這個:

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()到上面程式碼範例的末尾。

引用自:https://stackoverflow.com/questions/6015757