Question Searching a generic list

goldford

Member
Joined
May 6, 2009
Messages
12
Programming Experience
1-3
Hi,

I have been reading extensively about searching generic lists in VB.NET with the usage of delegates. However, I still cannot seem to grasp how to achieve what I want to, which I believe is frustratingly simple!

I have a list populated with instances of an object with three parameters (fields/variables). When I receive a new object to add to the list I want to search the list for the "layer" field. If the field matches then I will replace that row (object) in the list with the new object, if no match is found then I will add it to the list.

My object:

VB.NET:
Expand Collapse Copy
Public Class LayertoAdd
Public Layer As String
Public QuanField As String
Public ClsField As String

Public Sub New(ByVal layer As String, ByVal QuanField As string, ByValClsField As String)

me.Layer = layer
Me.QuanField = QuanField
Me.ClsField = ClsField

End Sub
End Class

My List Variable:
VB.NET:
Expand Collapse Copy
Private m_LayersFields As List(Of LayerToAdd) = New List(Of LayerToAdd)

This list is going to be a property of the object. The property:
VB.NET:
Expand Collapse Copy
Public Property LHabParamList()

Get
Return m_LayersFields
End Get

Set (ByVal value)

Dim pLayerToAdd As LayerToAdd
pLayerToadd = value

 ' Here is where I am confused.  I just want a boolean return 
' true if the list contains a match in the .layer field of the LayerToAdd object
If m_LayersFields.Contains(...) = True Then
Else m_LayersFields.Add(pLayerToAdd)
End If

End Set
End Property

So I have not come up with the predicate function yet. I am stumped!
 
I would suggest you take a look at this link:

How to Use the Action and Predicate Delegates

VB.NET:
Expand Collapse Copy
Private pLayerToAdd As LayerToAdd
Private ListLayerToAdd As New List(Of LayerToAdd)

VB.NET:
Expand Collapse Copy
pLayerToAdd = New LayerToAdd("somevalue", "someothervalue", "anothervalue")
Dim idx As Integer = ListLayerToAdd.FindIndex(AddressOf FindByLayer)
If idx = -1 Then
     ListLayerToAdd.Add(pLayerToAdd)
Else
     ListLayerToadd.Item(idx) = pLayerToAdd
End If

VB.NET:
Expand Collapse Copy
Private Function FindByLayer(ByVal layer As LayerToAdd) As Boolean
     Return layer.Layer = pLayerToAdd.Layer
End Function
 
Thanks, Ty. That article was just what I was looking for.

Also, thx MattP. I had seen this article but will take a closer look at it in the coming days.
 
Back
Top