VB.NET Lambda表达式而不是迭代器

时间:2013-04-05 15:51:12

标签: vb.net lambda

我很确定这可以重写为Lambda表达式,但每次尝试都会失败。我知道,C#Lambda读得更干净,但我坚持使用VB.NET。这是代码 - 有人能指出我正确的方向吗?谢谢!

For Each e As EventToMonitor In Events
    If e.TypeID = 1 Then
        If ("," & e.Values).Contains("," & b.ChoiceID & ",") Then
            Notify(cacheValues, e, "Event notification (button press)", "Button pressed: " & b.Text & " on screen: " & b.GroupBox.Text & Environment.NewLine & 
                       "User: " & cacheValues.CurrentUserName & Environment.NewLine & _
                       "Pressed at: " & Date.Now.ToShortDateString & " " & Date.Now.ToShortTimeString)
        End If
    End If
Next

1 个答案:

答案 0 :(得分:1)

如果您想将整个事物转换为lambda,那么这样的事情应该有效:

Events.Where(Function(e) e.TypeID = 1 AndAlso ("," & e.Values).Contains("," & b.ChoiceID & ",")) _
      .ToList() _
      .ForEach(Sub(e) Notify(cacheValues, e, "Event notification (button press)", "Button pressed: " & b.Text & " on screen: " & b.GroupBox.Text & Environment.NewLine & _
              "User: " & cacheValues.CurrentUserName & Environment.NewLine & _
              "Pressed at: " & Date.Now.ToShortDateString & " " & Date.Now.ToShortTimeString))

老实说,我通常更喜欢使用它们来过滤结果或构建集合:

Dim eventsList = Events.Where(Function(e) e.TypeID = 1 AndAlso ("," & e.Values).Contains("," & b.ChoiceID & ","))

For Each e As EventToMonitor In eventsList
    Notify(cacheValues, e, "Event notification (button press)", "Button pressed: " & b.Text & " on screen: " & b.GroupBox.Text & Environment.NewLine & 
               "User: " & cacheValues.CurrentUserName & Environment.NewLine & _
               "Pressed at: " & Date.Now.ToShortDateString & " " & Date.Now.ToShortTimeString)
Next