2014-10-02 89 views
0

我現在做一些低效這樣的:如何循環訪問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

回答

0

在字典中的每個條目返回爲具有財產價值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