The problem with the Find() function of List
Dim instance As New Predicate(Of T)(AddressOf HandlerMethod)
The HandlerMethod() would then contain the logic for determining which instance from the list to return. The BIG problem with this is that you can't pass any other parameters in to the method which means you have to either hardcode the search criteria into the function or if you are trying to match an existing object to one already in the List having to assign it to a global variable. In C# the solution to this is to use anonymous methods but that is not an option in VB.Net.
I spent a couple of hours wrestling with this and was about to resort to just looping through the list until i got a match when i found the following article:
http://blogs.sarkhouston.com/hdierking/archive/2006/03/26/3188.aspx
In this the writer provided a workaround so that an object could be passed in as a parameter. The solution is a little convaluted but it works. Anyway as i was looking at his could i saw an even simpler solution.
For this to work your class will need to implement the IEquatable(Of T) interface
public class MyClass
implements IEquatable(Of MyClass)
private _name as string
public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Function Equals1(ByVal other As Regulation_Type) As Boolean Implements System.IEquatable(Of Regulation_Type).Equals
return me._name = other._name
end function
dim myList as new List(of MyClass)
dim currentMyClass as MyClass
currentMyClass = New MyClass
currentMyClass.Name = "Bob"
if myList.contains(currentMyClass) then
currentMyClass = myList.Find(New System.Predicate(Of MyClass)(AddressOf currentMyClass.Equals1)
end if
4 comments:
Thanks a million. That really helped me out.
Fantastic. Thanks very much for this - I was really struggling trying to find a generic way to do this.
Glad to be of help.
I stumbled upon your solution and I worked just fine at my first shot.
Thanks for reducing a bit the entropy of the .NET world :-)
Post a Comment