1

我正在使用以下代码:

    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

哪个输出:

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

当我取消注释要添加到集合的行时answersToQuestions.Add(question.Quest_ID, answer),它会输出此错误:

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).

添加失败。提供了重复的键值。

似乎没有任何重复。如何将所有这些项目添加到我的收藏中?

谢谢。

4

2 回答 2

4

您正在使用 Visual Basic 特定Collection类(实际上是用于遗留代码库)。

它的Add方法期望通过Itemthen Key,而不是Keythen Item

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

您已经有了 Key True...

正如@Paul Grimshaw 所建议的那样,我还建议使用诸如Dictionary(Of TKey,TValue).

于 2012-10-08T14:41:58.693 回答
2

你可以试试这个看看它是否有效:

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
于 2012-10-08T14:38:22.690 回答