Results 1 to 2 of 2

Thread: List.Contains

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Dec 2013
    Location
    Earth
    Posts
    230

    List.Contains

    Hello everyone!

    If I have a list and want to search to see if it has a specific item in it, I use List.contains. However I found out that one cannot search for a custom made object. Why is this so? How can I fix it?

    Thanks all,

    ~Nic

    vb Code:
    1. Option Strict On
    2. Option Explicit On
    3.  
    4. Public Class Form1
    5.  
    6.     Dim List1 As New List(Of ComplexObject)
    7.  
    8.     Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
    9.  
    10.         With List1
    11.  
    12.             .Add(New ComplexObject(New Point(5, 5), 10, "string1"))
    13.             .Add(New ComplexObject(New Point(6, 10), 20, "string2"))
    14.             .Add(New ComplexObject(New Point(8, 15), 30, "string3"))
    15.             .Add(New ComplexObject(New Point(10, 20), 40, "string4"))
    16.  
    17.         End With
    18.  
    19.         MsgBox(List1.Count & " items on list.")
    20.  
    21.     End Sub
    22.  
    23.     Private Sub ButtonCheck_Click(sender As Object, e As EventArgs) Handles ButtonCheck.Click
    24.  
    25.         Dim N As New ComplexObject(New Point(8, 15), 30, "string3")
    26.  
    27.         If List1.Contains(N) Then
    28.             MsgBox("Yes")
    29.         Else
    30.             MsgBox("No")
    31.         End If
    32.  
    33.     End Sub
    34.  
    35.     Private Sub ButtonRemove_Click(sender As Object, e As EventArgs) Handles ButtonRemove.Click
    36.  
    37.         List1.Clear()
    38.  
    39.         MsgBox(List1.Count & " items on list.")
    40.  
    41.     End Sub
    42.  
    43. End Class
    44.  
    45. Public Class ComplexObject
    46.  
    47.     Dim P As Point
    48.     Dim N As Int32
    49.     Dim S As String
    50.  
    51.     Public Sub New(P_New As Point, N_New As Int32, S_New As String)
    52.  
    53.         P = P_New
    54.         N = N_New
    55.         S = S_New
    56.  
    57.     End Sub
    58.  
    59. End Class

  2. #2
    Frenzied Member IanRyder's Avatar
    Join Date
    Jan 2013
    Location
    Healing, UK
    Posts
    1,232

    Re: List.Contains

    Hi,

    You need to override the Equals Method to test for the equality of a complex object. Have a look at the Find Method below which demonstrates how to do this:-

    List(Of T).Find Method (Predicate(Of T))

    Hope that helps.

    Cheers,

    Ian

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width