user1477388
user1477388

Reputation: 21430

Can't Add to Collection in VB.NET (Duplicate Exception)

I am using the following code:

    Dim questions = db.Tbl_Challenge_Questions.Where(Function(x) x.Quest_Challenge_ID = challengeId)

    Dim answersToQuestions = New Collection

    For Each question As Tbl_Challenge_Question In questions

        Dim questionId = question.Quest_ID
        Dim answer = question.Tbl_Challenge_Question_Answer.Where(Function(x) x.QAns_Question_ID = questionId).FirstOrDefault.QAns_Answer()
        Debug.Print("Quest_ID=" + question.Quest_ID.ToString)
        Debug.Print("answer=" + answer)
        'answersToQuestions.Add(question.Quest_ID, answer)

    Next

Which outputs this:

Quest_ID=1
answer=True
Quest_ID=2
answer=150 minutes
Quest_ID=3
answer=True
Quest_ID=4
answer=False
Quest_ID=5
answer=Continuing to smoke

When I un-comment the line to add to the collection answersToQuestions.Add(question.Quest_ID, answer), it outputs this error:

Quest_ID=1
answer=True
Quest_ID=2
answer=150 minutes
Quest_ID=3
answer=True
A first chance exception of type 'System.ArgumentException' occurred in Microsoft.VisualBasic.dll
The program '[4948] WebDev.WebServer40.EXE: Managed (v4.0.30319)' has exited with code 0 (0x0).

Add failed. Duplicate key value supplied.

There don't appear to be any duplicates. How can I add all of these item to my collection?

Thanks.

Upvotes: 1

Views: 1593

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239714

You're using the Visual Basic specific Collection class (meant for legacy code bases, really).

Its Add method expects to be passed Item, then Key, not Key then Item:

public void Add(
    Object Item,
    string Key,
    Object Before,
    Object After
)

You already have a value in there with the Key True...

As @Paul Grimshaw recommends, I'd also recommend using a generic type such a Dictionary(Of TKey,TValue).

Upvotes: 4

Paul Grimshaw
Paul Grimshaw

Reputation: 21034

Can you try this to see if it works:

Dim questions = db.Tbl_Challenge_Questions.Where(Function(x) x.Quest_Challenge_ID = challengeId)

    Dim answersToQuestions = New Dictionary(Of Integer, String)

    For Each question As Tbl_Challenge_Question In questions

        Dim questionId = question.Quest_ID
        Dim answer = question.Tbl_Challenge_Question_Answer.Where(Function(x) x.QAns_Question_ID = questionId).FirstOrDefault.QAns_Answer()
        Debug.Print("Quest_ID=" + question.Quest_ID.ToString)
        Debug.Print("answer=" + answer)
        answersToQuestions.Add(question.Quest_ID, answer)
     Next







    Next

Upvotes: 2

Related Questions