重复添加数据列表的时间

时间:2016-01-31 14:37:41

标签: vb.net

类似于像这样的python代码

 while listCompanion :

在vb net中我试图使用代码For Each kvp In listCompanion但是失败了

Dim listCompanion As New Dictionary(Of String, String()) From {"dessy", New String() {"age: 21", "gender: girl"}}
Dim kvp As KeyValuePair(Of String, String())
ListBox1.Items.Clear()
For Each kvp In listCompanion
  Dim member As String = String.Format("{0} = {1} - {2}", kvp.Key, kvp.Value(0), kvp.Value(1))
  ListBox1.Items.Add(member) 'I want every additions will enter the listbox
  If listCompanion.Count < 2 Then    'Error here
       listCompanion.Add({"jony", New String() {"age: 25", "gender: boy"}})
  End If
next

当您想要添加数据列表时,For Each实际上不再工作

我希望在listCompanion.Add({"jony", New String() {"age: 25", "gender: boy"}})

之后

可以重复For Each kvp In listCompanion

1 个答案:

答案 0 :(得分:0)

有三个问题不允许您的代码编译。

首先,你在listCompanion的初始化中错过了几个大括号,

Dim listCompanion = New Dictionary(Of String, String()) From 
    { {"dessy", New String() {"age: 21", "gender: girl"}}}

其次,当您向listCompanion添加新元素时,花括号太多了。

If listCompanion.Count < 2 Then    'Error here
    listCompanion.Add("jony", New String() {"age: 25", "gender: boy"})
End If

最后你不能在循环时更改listCompanion,所以如果你想将KeyValuePair也添加到Listbox项目,那么你应该在开始循环之前添加它

Dim kvp As KeyValuePair(Of String, String())
ListBox1.Items.Clear()

If listCompanion.Count < 2 Then    'Error here
    listCompanion.Add("jony", New String() {"age: 25", "gender: boy"})
End If

For Each kvp In listCompanion
    Dim member As String = String.Format("{0} = {1} - {2}", kvp.Key, kvp.Value(0), kvp.Value(1))
    ListBox1.Items.Add(member) 'I want every additions will enter the listbox
Next