views:

33

answers:

3

Imagind I have the following in VB:

function doSomething()

    From ou In ctxt.Users.Where(Function(p) p.UserName = username)
    ...

end function

how can I send the filter as parameter (something like below)?

function doSomething(filter as whatTypeHereAndHowToInstantiateInCallingFunction)

    From ou In ctxt.Users.Where(filter)
    ...

end function

thanks

A: 

Your filter parameter type should be Expression<Func<bool>> I believe. Then you can pass a lambda expression to it that you can use as a variable.

If you're using LINQ-to-objects, though, you may just want to use Func<bool> as the parameter type.

John Bledsoe
Sorry about C# syntax. I'm not sure of VB equivalent but I'm sure you can figure that out.
John Bledsoe
No need for an Expression with linq-to-objects. A predicate is good enough.
Joel Coehoorn
+2  A: 

You could start with something like this:

Sub doSomething(Of T)(filter as System.Func(Of T, Boolean))

    From ou In ctxt.Users.Where(filter)
    ...

End Sub

I don't know the type of ctxt.Users, but you could just remove the generic T with your type and pass a Func(of YOURTYPE, Boolean) to doSomething.

Then you can use it like this:

doSomething(Function(p) p.UserName = username)
dkson
+1  A: 

You could also use a predicate, like this

<TestMethod()> _
Public Sub test1()
    Assert.AreEqual("a", WhereExample(Function(x) x = "a"))
End Sub

Public Function WhereExample(ByVal filter As Predicate(Of String)) As String
    Dim str = New String() {"a", "b", "c"}
    Return str.ToList.FindAll(filter).FirstOrDefault
End Function
Iain