0

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

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

9 Comments

Give him the "using"/"imports" statement as well, and I'll upvote it.
"using System.Linq;" in C#.
oh, I see, makes sense indeed
DAMN ! I just realised the whole is in VB..... I work so much in both that they are now one and the same.
Somebody downvoted you. But I'm upvoting now. Give him the case-insenstive string-check-compare and you'll have a great answer.
|
0

You could use Linq...

For Each p in projlist
    If Not projlist.Any(Function(pl) (pl.ID = proj.ID)) Then prodlist.Add(proj)
Next

(Replace ID with your object's property name)

2 Comments

Add the using/imports statement he needs........for "Any".....and provide a case insensitive version of the equals check........and I'll upvote.
@granadaCoder: I didn't include the import statement because the code above will compile without it, and in the OP's post he said proj is Object (int,string), I'm comparing the integer IDs in my answer so case is irrelevant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.