How to pass a lambda expression as argument of a parameter in a method?

Asked

Viewed 185 times

5

Is there any way to pass a lambda expression as a parameter argument in a method? For example:

Private Sub Metodo(Expressao As ?)
    Lista = Lista.Where(Expressao)
End Sub

2 answers

5


The most adopted way is to use a predefined delegate, such as the Func(Of TSource, Boolean):

Private Sub Metodo(Of TSource)(Expressao As Func(Of TSource, Boolean))
    Lista = Lista.Where(Expressao)
End Sub

The TSource is generic, if you know the specific type you can use it. If you are a Integer, can be:

Private Sub Metodo(Expressao As Func(Of Integer, Boolean))
    Lista = Lista.Where(Expressao)
End Sub

To call is not as convenient as C#:

Metodo(Function(x) x = 0)

I put in the Github for future reference.

Documentation.

4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.