【问题标题】:Can't Add to Collection in VB.NET (Duplicate Exception)无法在 VB.NET 中添加到集合(重复异常)
【发布时间】:2012-10-08 14:34:21
【问题描述】:

我正在使用以下代码:

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

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

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

谢谢。

【问题讨论】:

  • 使用强类型集合不是更好吗,比如 Dictionary(of Integer, String)?
  • Collection 是什么类型请提供代码或 MSDN 链接
  • @Jodrell - 我怀疑它是 this one,因为它是我能找到的唯一一个 a) 称为 Collection,b) 不是通用的,c) 有一个 Add 方法接受多个参数。
  • @Damien_The_Unbeliever,是的,很明显。在不经常使用它之后,人们忘记了 Microsoft.VisualBasic 命名空间的好奇心。

标签: asp.net-mvc vb.net collections


【解决方案1】:

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

它的Add 方法期望通过Item,然后是Key,而不是Key,然后是Item

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

您已经在其中使用密钥 True...

正如@Paul Grimshaw 建议的那样,我还建议使用Dictionary(Of TKey,TValue) 这样的泛型类型。

【讨论】:

    【解决方案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
    

    【讨论】:

    • 效果很好。谢谢。我仍然习惯于 VB.NET 中不同类型的集合。在我的原生 PHP 中,只有一个:array() :)
    • @user1477388,IMO 通常避免使用 Microsoft.VisualBasic 命名空间
    • 对我来说,很难掌握哪些函数属于哪个命名空间。
    猜你喜欢
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    • 2018-08-11
    • 2019-07-05
    • 2021-12-21
    • 2023-04-09
    • 2013-10-07
    相关资源
    最近更新 更多