Question about generic Finds

B

B. Chernick

I'm studying for a cert and hacking some code. I have a generic List(of T)
declared which contains a number of instances of a class. What I would like
to do is setup a search predicate (?) on Find that would return a class
instance with a unique property value. (But I'm not clear on the concept.)

What I have so far is a function within the the class defined as: Private
Function test(ByVal x As Class1) As Boolean. The compiler will then accept
Class1Instance = List1.Find(AddressOf test).

I suppose I could define a variable outside the test function but that seems
sloppy. How do you set up a delegate so that you can pass a search parameter
directly from the Find itself? (Can you?)
 
B

Branco Medeiros

B. Chernick said:
I'm studying for a cert and hacking some code.  I have a generic List(of T)
declared which contains a number of instances of a class.  What I wouldlike
to do is setup a search predicate (?) on Find that would return a class
instance with a unique property value.  (But I'm not clear on the concept.)

What I have so far is a function within the the class defined as: Private
Function test(ByVal x As Class1) As Boolean.  The compiler will then accept
Class1Instance = List1.Find(AddressOf test).  

I suppose I could define a variable outside the test function but that seems
sloppy.  How do you set up a delegate so that you can pass a search parameter
directly from the Find itself?  (Can you?)

One way to do it is to define the function in a separate class, one to
which you could pass the search parameter.

<example>
Class NameFinder
Private mName As String
Public Sub New(NameToFind As String)
mName = NameToFind
End Sub

Function FindByName(Item As Class1) As Boolean
Return Item.Name = mName
End Function
End Class

'...

Dim F As New NameFinder("John Doe")
ClassInstance = List1.Find(AddressOf F.FindByName)
</example>

Hope this helps.

(and good luck on the exam)

Branco.
 
B

B. Chernick

Actually that's approximately what I did. Thanks.

(It just seems a bit non-intuitive, not being able to pass the test
parameter directly to the Find command.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top