如何循环访问VB.Net数组?

问题描述:

我现在做一些低效这样的:如何循环访问VB.Net数组?

' Returns a collection of selected choices in a multichoice field 
Dim MyField As NS.ChoiceValues = CType(Me.Form.Fields("Field").Value, NS.ChoiceValues) 

If MyField.Choices.Item("Value 1") IsNot Nothing Then 
    ' Do stuff to database choice Value 1, which has id 100 
End If 

If MyField.Choices.Item("Value 1") Is Nothing Then 
    ' Do other stuff to database choice Value 1, which has id 100 
End If 

If MyField.Choices.Item("Value 2") IsNot Nothing Then 
    ' Do stuff to database choice Value 2, which has id 200 
End If 

If MyField.Choices.Item("Value 2") Is Nothing Then 
    ' Do other stuff to database choice Value 2, which has id 200 
End If 

... 

这是非常低效的,当选择的数量值增加变得不可读。所以我想更新一下:

Dim Field1Choices As New Dictionary(Of Integer, String) From { 
    {100, "Value 1"}, 
    {200, "Value 2"}, 
    {300, "Value 3"}, 
    {400, "Value 4"} 
    ... 
} 

For Each FieldChoice As String In Field1Choices 
    If MyField.Choices.Item(var_a) ' var_a should be "Value 1", "Value 2", etc. 
     DoStuff.WithCoice(Me.Database, "SomeTable", var_b) 'var_b should be 100, 200 etc. 
    End If 
Next 

很明显,这是行不通的。因为我的数组包含整数和字符串,所以For Each FieldChoice As String In Field1Choices不起作用。

如何循环访问Field1Choices数组,使var_avar_b得到数组值的值?

+0

字典包含键 - 值对:'对于每个FieldChoice作为KeyValuePair(整数,字符串)在Field1Choices'然后你得到这样的键/值:'FieldChoice.Key'和'FieldChoice.Value'。 – 2014-10-02 16:40:11

在字典中的每个条目返回为具有财产价值KeyValuePair类型和属性关键
在For Each循环中,您不需要声明迭代器的类型。它由查看枚举类型的编译器正确识别。在这种情况下,你的Dictionary有一个Integer键和一个字符串值。所以,你的KeyValuePair迭代包含整数类型的密钥和字符串类型的字典中的每个条目的值

Dim Field1Choices As New Dictionary(Of Integer, String) From { 
    {100, "Value 1"}, 
    {200, "Value 2"}, 
    {300, "Value 3"}, 
    {400, "Value 4"} 
} 

For Each FieldChoice In Field1Choices 
    Dim var_A = FieldChoice.Value 
    Console.WriteLine(var_A) 

    DIm var_B = FieldChoice.Key 
    Console.WriteLine(var_B) 

    'DoStuff.WithCoice(Me.Database, "SomeTable", var_B) 'var_b should be 100, 200 etc. 

Next