how to send LINQ filter as parameter
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)开发者_如何学JAVA?
function doSomething(filter as whatTypeHereAndHowToInstantiateInCallingFunction)
From ou In ctxt.Users.Where(filter)
...
end function
thanks
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)
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.
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
精彩评论