Hendrik Breezy Hendrik Breezy - 3 months ago 32
Vb.net Question

Visual Basic Find String in List Of Object

Greeting. I'm currently kinda stuck finding a String in a list of

Object (int,string)


I want to check if the String is already contained in the List - if not add it.

The regular
<List>.Contains()
doesn't work since I am initializing a new Object before inserting it.

Here is my code:

Dim command = New SqlCommand(query, connection)
Dim reader = command.ExecuteReader()
While reader.Read

Dim projID = reader.Item("DB_ID")
Dim projName = reader.Item("Project")
Dim proj = New KMProject(projName, projID)
projList.Add(proj)

End While
reader.Close()
=============================== ProjList having some items already =====================================
query = ...

command = New SqlCommand(query, connection)
reader = command.ExecuteReader()
While reader.Read

Dim projID = reader.Item("DB_ID")
Dim projName = reader.Item("Project")
Dim proj = New KMProject(projName, projID)
===============Below this section im stuck while verifying if this String is already in the List ===================================
For Each p In projList
If projList.Contains() Then
Else

projList.Add(proj)
End If
Next

Answer

In my opinion, your best bet here is LINQ :

If Not progList.Any(Function(x) x.Name = "Your string to check") Then
    /*Add the thing*/
End If

Don't forget you have to add the Imports statement:

Imports System.Linq;